Use the Apache Velocity template engine to build a Web site quickly

Source: Internet
Author: User
Tags end html page interface variables php and variable java web access
apache| templates

Based on the development of Java Web site, many people use JSP as a front-end Web production technology, especially in the country. There are usually some problems with this technique, and you can look at these problems by simply analyzing the Web site development process. Typically, Web sites are developed in the following two ways:

After the site function is determined, the UI (interface) portion of the Web page is designed by the designer, and then the programmer adds code display logic to it (such as looping, judging the results of the display data). This is the usual JSP page production, of course, this part can be finished by the art template, and then by the JSP engineer to it for the prototype to create the corresponding JSP page.

After the site function is determined, the UI (interface) section of the Web page is designed by the designer, and then the Web page producer adds code display logic to it (such as looping, judging the results of the display data). In this step of JSP page production, Web page makers usually only need to understand JavaScript and HTML, under the guidance of engineers learn how to embed the JSP taglib tag, and then the art template for the prototype production JSP pages.

Obviously the latter approach is more clearly divided than the previous one. However, in many small companies, or project emergency, JSP Web page production and background program development are the same person, which undoubtedly increased the burden on the programmer. The latter situation also has two disadvantages, one is that Web page makers must learn how to use JSP taglib, which will increase the burden of web page production staff; second, if the page is redesigned because of customer requirements, then in either case, the Web page maker will embed the display logic in the JSP page.

Although JSP is better than PHP and ASP in terms of performance and taglib usage, it is designed to resemble the language of a server page such as PHP, the technique of embedding scripting languages in a page. This makes it much faster than the traditional CGI scripting language development model, but confuses the daemon logic with the page display.

   developing a Web site in MVC mode

Now more Web sites are being produced using a pattern called MVC, which is the division of work on the site, divided into m (model, models), V (view, view) and C (Controller, Controller).

m (model, models) m includes background transaction logic, code that really handles transactions, and business logic, which are the most important parts of the entire site. Usually this part of the code is relatively stable, does not often change, is a change will not affect the front page.

V (view, view) v is the display portion of a Web page that accepts results or data from a background program for display. The V view is usually a larger part of the change, such as the daily update of the Web interface, and every other time the style of the page will create a lot of changes in the V view part of the work.

C (Controller, Controller) C transfer control between the view and the model, and call the corresponding view to display the data returned according to the requirements, mainly responsible for the scheduling work.

What is the benefit of this division of responsibility? It simplifies the work of all the people involved in the software development process, so that changes to the different parts of the system usually do not affect the rest of the work. For example, modify the background of some programs do not affect the foreground of the page display, the front page changes do not affect the background program development.

This division of division is much better than the way JSP confuses code logic and display layers. Therefore, more and more foreign programmers are constantly proposing alternative JSP scheme. Among the many scenarios, technologies based on the Java template engine stand out, notably the velocity and Webmacro two template technologies.

   Velocity Template Engine

The design idea of the template engine was first proposed by Webmacro and was applied to a famous search engine Later, the 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 view portion of MVC. Velocity can be applied to any Java program that requires formatting data display. 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." ”

The advantage of using velocity is that:

Easily integrated into a wide range of program areas;

Provides a clear and simple syntax for Web page makers;

Because the templates and code are separate, they can be independently developed and maintained;

The velocity engine can be easily integrated into some Java runtime environments, especially in the servlet;

Velocity allows a template to access common methods in any environment object.

The great thing about velocity is that it strictly distinguishes between the responsibilities of the program development function. It does this by restricting the objects that the template might access (that is, the objects that the daemon allows them to get). This means that Web designers can focus only on the display (view) of the data, while programmers focus on how to write the control layer (Controller) of the program, business logic, and data Management (Model). This is the typical MVC development model that simplifies development and increasingly complex application and maintenance work.

Velocity is best at doing things including:

Web site production based on Servlet;

Java and SQL code generation;

XML processing and transformation;

Word processing, such as generating TRF files.

However, the most used velocity is in the Java servlet based Web page program to do the engine to generate Web pages, in place of JSP and other technologies. In addition to its ease of use, it provides a powerful template language to display and manipulate data. Note that it is important not to generate data, because the build work should be part of the program logic.

Velocity is ideal for Java 2 platform,enterprise Edition Web site development in lieu of JSP, do output page technical work. Although JSP is included in the Java EE specification, the Java EE itself does not need a JSP.

   use velocity to make Web pages

How does velocity work? While most of the velocity applications are based on servlet Web pages, a more general Java application is used to illustrate how velocity works.

Any velocity application includes both template making and program parts. By convention, HelloWorld is used as an example of the first program.

1. Template-Making template sample HELLOSITE.VM is as follows (although it is not HTML-oriented but easily converted to an HTML page):

        Hello $name!  Welcome to $site world!

2. Java Program Section

Here is the Java code:

          Import;import;import org.apache.velocity.Template; Import Org.apache.velocity.velocitycontext;public class Helloworld{public static void Main (string[] args) throws exception{/* a 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 = NE W 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 these two files in the same directory, compile and run, and the result is:

        Hello Eiffel qiu!  Welcome to Http:// World

To keep it running smoothly, download the velocity run package from the Velocity's website place the path of the velocity jar package in the classpath of the system. This will allow you to compile and run the above program successfully.

The program is simple, but it clearly illustrates the basic workings of velocity. The other parts of the program are basically fixed, and the main part is in the following sections of code.

Velocity get template file, get template reference:


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

Initialize the environment and put the data into the environment:


        Velocitycontext context = new Velocitycontext (); Context.put ("Name", "Eiffel Qiu"); Context.put ("Site", "http:// ");

Initialize the velocity template engine:


        Velocityengine ve = new Velocityengine (); Ve.init ();

Combine environment variables with output parts:


          StringWriter writer = new StringWriter (); T.merge (context, writer);/* Show the World */system.out.println (writer.tostr
       ing ()); 

This section 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.


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, where view, Modle and controller work independently, and the modification of one side does not affect other changes.

The relationship between them through the environment variables (context) to achieve, of course, the Web page makers and the background program to mutually agreed on the passing variables, 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 a good variable name, you can work independently. No matter how the page changes, as long as the variable name unchanged, the background program need not change, the front page can also be arbitrarily modified by the Web page production staff.

Usually simple variable names do not meet the needs of Web page production to display data, such as often looping some data sets, or based on the value of some data to determine how to display the next step of the data.

Velocity also provides a simple syntax for looping and judging to meet the needs of web making. Velocity provides a simple template language that can be used by front-end Web makers, which are simple enough for most people who know JavaScript to grasp quickly, even simpler than JavaScript.

Of course, this simplicity is deliberate, because velocity does not need to be able to do anything, but only focus on what it should be done. The view layer should not contain more logic, and velocity's simple template syntax perfectly satisfies all the need for the display logic of the page and does not result in situations like JSP destroying the system because of an infinite loop statement.

Related Article

Alibaba Cloud 10 Year Anniversary

With You, We are Shaping a Digital World, 2009-2019

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.