How to use the Velocity template engine to develop a Web site

Source: Internet
Author: User
Tags add naming convention variables php and php code variable tostring java web

Based on the development of Java Web site, many people use JSP as a front-end Web production technology, especially in the domestic. There are usually some problems with this technique, and I think about how we develop the site, usually in several ways:

1: After the function is determined, the UI part of the Web page is designed by the designer, and then the programmer adds the code display logic to it (such as the loop, to judge the result of the display data). That is, the usual JSP page production, of course, this part can be completed by the art template, and then the JSP engineer to continue with it as a prototype to create the corresponding JSP page.

2: After the function is determined, by the art design Web page UI (interface) part, then by the Web page producer adds the code to display the logic (for example loop, the judgment displays the data result), in this step JSP page production, the page producer (usually only understands the JavaScript and the HTML Under the guidance of the engineer, learn how to embed the JSP taglib tag, and then make the JSP Web page as the prototype of the art template.

Obviously the latter way is more specific than the previous one, and then in many small companies, or projects in a hurry, JSP web production and background program development are the same person. This undoubtedly increases the burden on programmers. The latter situation is better than the previous one, but it has two disadvantages: one: Web page makers must learn how to use JSP taglib, which undoubtedly increased the burden on web-makers. Two: If the page because of the customer's request from the new design, then regardless of that situation web page production staff will be new to display logic embedded JSP page.

In this respect, JSP does not do well, although it is much better than PHP and ASP in terms of performance and taglib, it is designed to resemble the Server page language of PHP, which is the technique of embedding scripting language in a page, although it is more developed than the traditional scripting language based on CGI The pattern is fast, but it confuses the background program logic with the page display, so it's a less-than-good design from this point of view. Think about how many PHP programs you see, in a bunch of. php files, you don't know what the background programs are, but the programs that are used to display the pages.

Now more Web site production using an MVC pattern, that is, the Web site production work division, respectively, for the M (model, models), V (view view), C (Controller Controller).

  • M (model, models) is also the background of the transaction logic, the real processing of the business code, business logic and so on. They are the most important part of the entire site, usually this part of the code is relatively stable, not often change, is not a change will not affect the front page.

  • V. (view view): That is, the display part of the Web page, which accepts the results or data from the background program, is displayed, but this part is usually a relatively large part of the change, such as the site's interface update is often to do things, every once in a while update the style of the page will cause View A large number of changes in the View section.

  • C (Controller Controller). Transfer control between the view and the model, and call the corresponding view to display the data returned by the model, mainly responsible for the dispatch work.

    What is the benefit of this division of responsibility? It simplifies the software development process of all the people involved in the work, so that different parts of the changes usually will not affect the other parts of the work, for example, I modified some of the background program algorithm, does not affect the front page display, front page changes do not affect the development of background programs. This division of division is much better than JSP confusing code logic with the display layer.

    So a growing number of foreign programmers are constantly proposing alternatives to JSP, in many scenarios, a Java template engine based technology to stand out, the most famous is Velocity and Webmacro two template technology.

    The design idea of the template engine was first put forward by Webmacro, and later applied to a famous search engine , this idea was gradually adopted by the Apache development team and presented as a subproject, which is now Velocity. The template engine is more closely related to the part of the view in MVC. It is often used as a kind of JSP alternative technology appearing in some foreign forums. But Velocity can be applied to any Java program that requires formatting data to be displayed.

    So what is Velocity exactly? Its official explanation is:

    "Velocity is a java-based template engine that allows anyone to use a simple and powerful template language to refer to objects defined in Java code"

    You may use Velocity for several reasons:

    1: It's easy to integrate in a variety of program areas.

    2: It provides a clear and simple syntax for Web page makers

    3: Because templates and code are separate, you can independently develop and maintain them separately.

    The 4:velocity engine can be easily integrated into some Java runtime environments, especially the Servlet.

    5:velocity enables templates to access common methods in any environment object.

    Velocity's strength lies in its strict division of responsibility for distinguishing between program development functions. It restricts the objects that the template might access (that is, the object that the daemon allows it to get) to achieve this. This means that Web designers can focus only on the display portion of the data (view view) While programmers focus on how to write the control layer (Controller, controller) and business logic and data management (model models) of the program, which is the MVC development model. MVC is now a widely accepted development model that simplifies development and increasingly complex application and maintenance work.

    What kind of work is Velocity best at?

    1: Web site production based on Servlet

    2:java and SQL code generation

    3:xml Processing and conversion

    4: Word processing, such as generating TRF files.

    But Velocity is the most used in the Java servlet based Web page program to generate Web pages of the engine, in place of JSP and other technologies. In addition to being easier to use, it provides a powerful template language to display and manipulate data, but it is important to generate data, because this work should be part of the logic of the program. Velocity is ideal for Java 2 Platform, Enterprise Edition Web site development as an alternative JSP to do the output page of the technical work, although the JSP included in the specification of Java EE, in fact, the Java-EE itself does not need JS P.

    How does Velocity work? Although most of the Velocity applications are based on Servlet Web page production. But to illustrate the use of Velocity, I decided to use a more general Java application to illustrate how it works.

    It seems that all language teaching begins with HelloWorld as an example of the first program. This is no exception.

    Any Velocity application includes two aspects:

    The first is: template making, in our case is HELLOSITE.VM:

    Its content is as follows (although not HTML-oriented, but it's easy to change to an HTML page)

    Hello $name! Welcome to $site world! second is the Java program section:

    Here is the Java code



    Import Org.apache.velocity.Template;

    Import Org.apache.velocity.VelocityContext;

    public class HelloWorld


    public static void Main (string[] args)

    Throws Exception


    /* I, get and initialize an engine * *

    Velocityengine ve = new Velocityengine ();

    Ve.init ();

    /* Next, get the Template * *

    Template t = ve.gettemplate ("HELLOSITE.VM");

    /* Create a context and add data * *

    Velocitycontext context = new Velocitycontext ();

    Context.put ("name", "Eiffel Qiu");

    Context.put ("Site", "");

    /* Now render the template into a stringwriter * *

    StringWriter writer = new StringWriter ();

    T.merge (context, writer);

    * Show the world * *

    System.out.println (Writer.tostring ());


    Put two files in the same directory, compile and run, and the result is:

    Hello Eiffel qiu! Welcome to World

    To keep it running smoothly, download the velocity run package from the Velocity's website and place the path of the velocity Jar package in the system Classpath, so you can compile and run the above program.

    The program is simple, but it gives you a clear idea of how Velocity works in general. The other parts of the program are basically fixed, and the main part is the following code

    Here Velocity gets the template file to get the template reference

    /* Next, get the Template * *

    Template t = ve.gettemplate ("HELLOSITE.VM"); Here, initialize the environment and put the data into the environment

    /* Create a context and add data * *

    Velocitycontext context = new Velocitycontext ();

    Context.put ("name", "Eiffel Qiu");

    Context.put ("Site", ""); Other code is fixed, but it's also important, but it's the same for each application:

    This is the initialization Velocity template engine

    /* I, get and initialize an engine * *

    Velocityengine ve = new Velocityengine ();

    Ve.init (); This is used to combine environment variables with output parts.

    StringWriter writer = new StringWriter ();

    T.merge (context, writer);

    * Show the world * *

    System.out.println (Writer.tostring ()); Remember, this will be different in future servlet applications, because the page output is not the same as the command-line output, and if used for Web page output, it will not go through the System.out output. This will be explained in a later tutorial .

    So let me summarize how Velocity really works :

    Velocity solves the problem of how data is passed between a Servlet and a Web page, and of course the mechanism for transmitting data is in the MVC pattern, that is, view and Modle, Controller work independently of each other, and the modification of one side does not affect the other. Over the environment variables (context) to achieve, of course, both sides of the Web page production side and the background program to each other to agree on the passing variables of the naming convention, such as the previous program example site, name variables, they are on the Web page is $name, $site. So long as the two sides agreed to the variable name, then the two sides can work independently. No matter how the page changes, as long as the variable name unchanged, then the background program does not need to change, the front page can also be arbitrarily modified by the Web page production staff. That's how Velocity works.

    You'll find that simple variable names usually don't meet the needs of Web-making display data, such as we often loop through some datasets, or decide how to display the next data based on the values of some data, Velocity also provides a loop, a simple syntax for judging, to meet the needs of web production. Velocity provides a simple template language for use by front page producers, and the template language is simple enough (most people who know JavaScript can quickly grasp it, which is much simpler than JavaScript), and of course this simplicity is deliberate, Because it does not need to do anything, the View layer should not contain more logic, the Velocity of the simple template syntax to meet all of your page display logic needs, which is usually enough, there will not be like JSP as a result of an infinite loop to destroy the system, JSP Can do a lot of things, Sun in the development of JSP 1.0 standard, not in time to limit the programmer in the JSP insert code logic, so that the early JSP code more like PHP code, although it is powerful, but for the display layer of logic, is not necessary, and will cause the MVC three layer of the logical structure of confusion.

  • 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: 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.