Develop your own template engine based on Velocity

Source: Internet
Author: User

Velocity is a Java-based template engine ). It allows anyone to simply use the template language to reference objects defined by Java code.

When velocity is applied to web development, the interface designer can develop a web site following the MVC Architecture in sync with Java program developers. That is to say, the page designer can only focus on the page display effect, java developers focus on business logic encoding. Velocity separates Java code from the web page, which facilitates the long-term maintenance of the web site, and also facilitates, PHP and freemarker provide an optional solution.

Most developers only understand the above section, that is, velocity can be used as the V of MVC, so there are a lot of Integrated Design of velocity and springmvc, velocity and struts. But few people are concerned about the significance of velocity as a template engine. Since it is a template engine, it should not be limited to the MVC field.

Velocity is far more powerful than Web site development. For example, it can generate SQL, postscript, and XML from templates, it can also be used as an independent tool to generate source code and reports, or as an integrated component of other systems.


The following code is a simple encapsulation of velocity. You can use velocity as a separate component and use it as a template engine for our applications.

Core code:
Package COM. ths. platform. framework. template; import Java. io. bufferedwriter; import Java. io. fileoutputstream; import Java. io. outputstream; import Java. io. outputstreamwriter; import Java. util. properties; import Org. apache. velocity. template; import Org. apache. velocity. velocitycontext; import Org. apache. velocity. app. velocity; import Org. apache. velocity. app. velocityengine; public class velocityparser {// template context PRI Vate velocitycontext maincontext; // template object private template maintemplate; // template engine private velocityengine; // template engine initialization parameter private properties; public static void main (string [] ARGs) {string filepath = "template/view. JSP "; velocityparser = new velocityparser (filepath); velocityparser. addtocontext ("title", "helloworld"); velocityparser. processtemplate ();} /*** @ Methodname: addtocontext * @ Description: add the parameter * @ Param key * @ Param value */Public void addtocontext (string key, object value) to the template context) {If (maincontext = NULL) {maincontext = new velocitycontext ();} maincontext. put (Key, value);}/*** @ methodname: addtocontext * @ Description: Initialize the template context * @ Param chainctx */Public void addtocontext (velocitycontext chainctx) {maincontext = new v Elocitycontext (chainctx);}/*** @ methodname: processtemplate * @ Description: output to the console */Public void processtemplate () {try {bufferedwriter writer = new bufferedwriter (New outputstreamwriter (system. out); If (maintemplate! = NULL) {maintemplate. merge (maincontext, writer);} writer. flush (); writer. close ();} catch (exception ex) {ex. printstacktrace () ;}/ *** @ methodname: processtemplate * @ Description: output to file * @ Param destpath */Public void processtemplate (string destpath) {try {outputstream OS = new fileoutputstream (destpath); outputstreamwriter writer = new outputstreamwriter (OS, "UTF-8"); If (Maint Emplate! = NULL) {maintemplate. merge (maincontext, writer);} writer. flush (); writer. close ();} catch (exception ex) {ex. printstacktrace () ;}}/*** initialize the template engine based on the template file * @ Param templatefile */Public velocityparser (string templatefile) {try {// create a template engine velocityengine = new velocityengine (); // obtain the initialization parameter properties = initproperties (); // initialize the template engine velocityengine. init (properties); // obtain the template object maintemplate = velocityengine. gettemplate (templatefile);} catch (exception ex) {system. out. println ("error processing template file:" + templatefile) ;}}/*** according to the template file and template context (parameter) initialize template engine * @ Param templatefile * @ Param chaincontext */Public velocityparser (string templatefile, velocitycontext chaincontext) {try {// create template engine velocityengine = new velocityengine (); // obtain the initialization parameter properties = initproperties (); // initialize the template engine velocityengine. init (properties); // obtain the template object maintemplate = velocityengine. gettemplate (templatefile); // set the template context maincontext = chaincontext;} catch (exception ex) {system. out. println ("error processing template file:" + templatefile) ;}/ *** @ methodname: initproperties * @ Description: sets the initialization parameter * @ return */private properties initproperties () {properties Properties = new properties (); // set to load the template file properties from classpath. setproperty (velocity. file_resource_loader_path, thread. currentthread (). getcontextclassloader (). getresource (""). getpath (); // solves the Chinese garbled properties of the template. setproperty (velocity. input_encoding, "UTF-8"); properties. setproperty (velocity. output_encoding, "UTF-8"); return properties ;}}

Template:
 <table>  <tr><td>$title</td></tr>  </table>


Run the main method to output the data generated after the template and parameters are merged on the console.
With this code, as long as the development process involves repetitive work and the output of any reports, as long as you can extract the template and perform other work, let it roll over.

Develop your own template engine based on Velocity

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.