Ext2.0 + struts2 + spring2.5 + ibatis2 + Hsqldb (Oracle) + velocity1.5 + semi-automatic "2"

2008-08-02  来源:本站原创  分类:Java  人气:254 

http://www.blogjava.net/ilovezmh/archive/2008/12/27/248570.html

The second part velocity1.5 template engine

First studied the velocity1.5 template engine is used to automatically generate some code, we know that when the framework of a project to build up, the background code is basically similar, this time I

They can write some common template, and then generates the appropriate code, and can save a lot of time and improve efficiency. To this end wrote a helper class, you can easily read the template and create a file.

There are two modes using the velocity, single-state forms and multi-state form, the general form of single-state enough, roughly divided into the following Buju:

1. Set the configuration file attributes (optional):

This step is mainly to modify resource loader, and encoding problems when reading the template

There are six resources velocity1.5 loader, the default resource loader is FileResourceLoader, the loader to load from the file system resources,

When the Velocity when used in Servlet, it is best to use ClasspathResourceLoader, the loader to load resources from the classpath,

That will be placed in the class path load template resources (such as in a jar). The use of consistent Servlet2.2 or later container, this is a relatively simple mechanism.

Properties p = new Properties();
p.setProperty("resource.loader", "class");
p.setProperty("class.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
p.setProperty(Velocity.ENCODING_DEFAULT, "GBK");
p.setProperty(Velocity.INPUT_ENCODING, "GBK");
p.setProperty(Velocity.OUTPUT_ENCODING, "GBK");

2. Initialized, calling method:

//Velocity.init();
       Velocity.init(p);

3. Set Template:

For example, the template on / WEB-INF/classes/a/b/c/foo.vm directory, that is, under the abc package under the src, it should be so to take, and

Template template = Velocity.getTemplate("/a/b/c/foo.vm");  Or
    Template template = Velocity.getTemplate("/a/b/c/foo.vm", "UTF-8");

But can not use a relative path, such as classes and templates on the same path for the use of Velocity.getTemplate ( "foo.vm") does not work,

Note that it reads the java of the Class and ClassLoader resource files are not the same.
4. The definition of VelocityContext, assume that it is the template to replace the contents of the

VelocityContext context = new VelocityContext();

For example, the template has to replace the contents of the $ (objName), you'll need to replace the contents placed into the context of:

context.put (key, value); key shall be "objName", value for the replacement value, such as the "User".

5. Replace Template Content

StringWriter sw = new StringWriter();
    template.merge(context, sw);

6. Obtained after replacing the contents of the template to generate file

// Create a directory
   File dir=new File(path);
   if(!dir.exists()){
    dir.mkdirs();
   }
   // Create a file
  File file = new File(dir.getPath(),fileName);
   if(!file.exists()){
      file.createNewFile();
   }
   PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
   out.println(sw.toString());
   out.close();

Helper class VelocityUtil.java code is as follows:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
/**
 *
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2008</p>
 * <p>Company: </p>
 * @author  I wish the Ming Hua Yuan
 * @version 1.0
 */
public class VelocityUtil {

        private VelocityContext context = null;   

        private Template template = null;   

        private String templateString = null ;   

        public void init(String propertiesPath) throws Exception {
            if (propertiesPath != null && propertiesPath.trim().length() > 0) {
                Velocity.init(propertiesPath);
            } else {
                Velocity.init();
            }
            context = new VelocityContext();
        }   

        public void init(Properties properties) throws Exception {
            Velocity.init(properties);
            context = new VelocityContext();
        }

        public void init() throws Exception {
            Properties p = new Properties();
            p.setProperty("resource.loader", "class");
            p.setProperty("class.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            // Set the encoding of the velocity
            p.setProperty(Velocity.ENCODING_DEFAULT, "GBK");
            p.setProperty(Velocity.INPUT_ENCODING, "GBK");
            p.setProperty(Velocity.OUTPUT_ENCODING, "GBK"); 

            Velocity.init(p);
            context = new VelocityContext();
        }

        /**
         * @param key
         * @param value
         */
        public void put(String key, Object value) {
            context.put(key, value);
        }   

        /**
         *  Setting the template
         * @param templateFile   Template file
         * @throws Exception
         */
        public void setTemplate(String templateFile) throws Exception {
            try {
                template = Velocity.getTemplate(templateFile);
            } catch (ResourceNotFoundException rnfe) {
                rnfe.printStackTrace();
                throw new Exception("  Error  :  Could not find a template   " + templateFile);
            } catch (ParseErrorException pee) {
                throw new Exception("  Solutions that template error   " + templateFile + ":" + pee);
            } catch (Exception e) {
                throw new Exception(e.toString());
            }   

        }   

        /**
         *  Setting the template
         * @param templateFile  Template file
         * @throws Exception
         */
        public void setTemplate(String templateFile, String characterSet)
                throws Exception {
            try {
                template = Velocity.getTemplate(templateFile, characterSet);
            } catch (ResourceNotFoundException rnfe) {
                rnfe.printStackTrace();
                throw new Exception("  Error  :  Could not find a template   " + templateFile);
            } catch (ParseErrorException pee) {
                throw new Exception("  Solutions that template error   " + templateFile + ":" + pee);
            } catch (Exception e) {
                throw new Exception(e.toString());
            }   

        }
        /**
         *  The input stream is converted to a string
         * @param is
         * @return
         * @throws IOException
         */
        public static String getStringFromStream(InputStream is) throws IOException {
            if (null == is)
                return null;
            try {
                InputStreamReader reader = new InputStreamReader(is);
                char[] buffer = new char[1024];
                StringWriter writer = new StringWriter();
                int bytes_read;
                while ((bytes_read = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, bytes_read);
                }
                return (writer.toString());
            } finally {
                if (null != is)
                    is.close();
            }
        }

        public void setTemplateString(String templateFile, String characterSet){     

            try {
                InputStream is = this.getClass().getClassLoader().getResourceAsStream(templateFile);
                templateString = getStringFromStream(is);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        /**
         *  Converted to text
         */
        public String toText() throws Exception {
            StringWriter sw = new StringWriter();
            try {
                template.merge(context, sw);
            } catch (Exception e) {
                throw new Exception(e.toString());
            }
            return sw.toString();
        }
        /**
         *  Converted to text
         */
        public String toTextWithTemplateString() throws Exception {
            StringWriter sw = new StringWriter();
            try {
                Velocity.evaluate(context,sw,"mystring",templateString);
            } catch (Exception e) {
                throw new Exception(e.toString());
            }
            return sw.toString();
        }

        /**
         *
         * @param fileName
         */
        public void toFile(String path,String fileName) throws Exception {
            try {
                // Replace the contents of a template
                StringWriter sw = new StringWriter();
                template.merge(context, sw);

                // Create a directory path
                File dir=new File(path);
                if(!dir.exists()){
                    dir.mkdirs();
                }
                // Create a file
                File file = new File(dir.getPath(),fileName);
                if(!file.exists()){
                    file.createNewFile();
                }

                PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
                out.println(sw.toString());
                out.close();
                /*
                PrintWriter filewriter = new PrintWriter(new FileOutputStream(fileName), true);
                filewriter.println(sw.toString());
                filewriter.close();
                */
            } catch (Exception e) {
                throw new Exception(e.toString());
            }   

        }

        /**
         *
         * @param fileName
         */
        public void toFileWithTemplateString(String path,String fileName) throws Exception {
            try {
                // Replace the contents of a template
                StringWriter sw = new StringWriter();
                Velocity.evaluate(context,sw,"mystring",templateString);

                // Create a directory path
                File dir=new File(path);
                if(!dir.exists()){
                    dir.mkdirs();
                }
                // Create a file
                File file = new File(dir.getPath(),fileName+".java");
                if(!file.exists()){
                    file.createNewFile();
                }

                PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
                out.println(sw.toString());
                out.close();
                /*
                PrintWriter filewriter = new PrintWriter(new FileOutputStream(fileName), true);
                filewriter.println(sw.toString());
                filewriter.close();
                */
            } catch (Exception e) {
                throw new Exception(e.toString());
            }   

        }

        public static void main(String[] args) {   

        }   

}

Usage:

VelocityUtil agt = new VelocityUtil();
 agt.init();
 agt.setTemplate("/com/zhu/templet/Model.vm");
 agt.put("package", varp.getProperty("package"));
 agt.put("object_name", varp.getProperty("object_name"));
 agt.put("author", PropertiesUtil.getProperty(varp,"author","UTF-8"));
 agt.put("company",PropertiesUtil.getProperty(varp,"company","UTF-8"));
 agt.put("list", list); 

 String path = System.getProperty("user.dir")+"\\"+varp.getProperty("srcfilepath")+"\\model\\";
 String fileName = varp.getProperty("object_name")+"Model.java";
 agt.toFile(path,fileName);

Which varp is to read a configuration file

The velocity template engine use and more use of VTL syntax, look for relevant information, I am here, there are some, a friend in need can contact me.

相关文章