How to develop a Web site using the Velocity template engine

Source: Internet
Author: User
Tags naming convention php server

Java-based Web development, many people use JSP as the front-end web-making technology, especially in the country. This technique usually has some problems, and I think about how we develop the site, usually in several ways:

1: After the function is determined, the UI (interface) part of the Web page is designed by the artist, and then the programmer adds the code display logic (such as looping, judging the result of displaying the data). That is, the usual JSP page production, of course, this part can be done by the artist template, and then by the JSP engineer to continue to use it as a prototype to create the corresponding JSP page.

2: After the function is determined, the UI (interface) part of the Web page is designed by the artist, and then the page maker adds the code display logic (such as looping, judging the result of displaying the data), in this step of the JSP page production, the Web maker (usually only knows JavaScript and HTML Under the guidance of the engineer, learn how to embed the JSP taglib tag and then prototype the JSP Web page with the artwork template.

Obviously the latter way is more specific than the previous one, and then in many small companies, or the project is very urgent situation, JSP Web page production and background program development are the same person. This undoubtedly increases the burden on the programmer. The latter case is better than the previous one, but it has two drawbacks: one: web-makers must learn how to use JSP taglib, which undoubtedly increases the burden on web page makers. Second: If the page because of customer requirements from the new design, then regardless of the circumstances of the Web page production staff to new embed display logic from new embedded JSP Web page.

In this respect, JSP does not do well, although from the performance point of view and the use of taglib, it is much stronger than PHP and ASP, but it is very similar in design PHP Server Page language, that is, in the page embedded script language technology, although it than the traditional CGI-based scripting language development The mode is fast, but it confuses the daemon logic with the page display, so it's a less-than-good design from this point of view. Think about the many PHP programs you see, and in a bunch of. php files, you have no idea what the daemon is, but the programs that are used to display the page.

Now more site production to adopt an MVC pattern, that is, the division of site production, respectively, m (model, models), V (view view), C (Controller controllers).

  • M (model, models) is also the transaction logic in the background, the code that really handles the transaction, the 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, that is, changes 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, but this part is usually a relatively large change, such as the site's interface update is often to do things, every time to update the style of the page will cause the View A large number of changes in the View section work.

  • C (Controller controllers). The control is passed between the view and the model, and the corresponding view is called as required to display the data returned by the model and is primarily responsible for scheduling work.

    What is the benefit of this division of responsibilities, it simplifies the software development process of all the relevant personnel work, so that the different parts of the modification will not usually affect the work of other parts, for example, I modified the background of some programs, the algorithm does not affect the foreground page display, foreground page modification does not affect the development of background programs. This division of labor is much better than JSP obfuscation of code logic and display layers.

    Therefore, more and more foreign programmers are constantly proposing alternatives to JSP, in many scenarios, a Java template engine based technology stand out, the most famous is Velocity and webmacro two kinds of template technology.

    The design idea of the template engine was first proposed by Webmacro, and later applied to a famous search engine www.altavista.com , which was gradually adopted by the Apache development team and presented as a sub-project, which is now Velocity. The template engine is more closely related to the view part of MVC. It is often used as a JSP alternative technology appearing in some foreign forums. But Velocity can be applied to any Java program that needs to display the formatted data.

    So what exactly is Velocity? Its official explanation is:

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

    You may use Velocity for several reasons:

    1: It is 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 operating environments, especially servlets.

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

    Velocity's strength lies in its strict division of responsibilities that distinguishes program development functions. It does this by restricting the objects that the template might access (that is, the objects that the daemon allows it to get). This means that the Web designer can focus only on the display of the data (the view) and the programmer's focus on how to write the program's control layer (Controller, controllers) and business logic and data Management (model), which is the MVC development pattern. MVC is now widely accepted as a development model that simplifies development and increasingly complex application and maintenance efforts.

    What kind of work is Velocity best at?

    1: servlet-based website production

    2:java and SQL code generation

    3:xml Processing and conversion

    4: Word processing, such as generating TRF files.

    However, Velocity is most often used in Java servlet-based web programs to generate Web pages in the engine to replace the JSP and other technologies. In addition to being relatively easy 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 program logic. Velocity is well suited for the technical work of the Web development of the Java 2 Platform, Enterprise Edition, as an alternative JSP for the output page, although JSP is included in the specification of the 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 authoring. But to illustrate the use of Velocity, I decided to adopt a more general Java application to illustrate how it works.

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

Any Velocity application is comprised of two areas:

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

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

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

Here is the Java code

Import Java.io.StringWriter;

Import Org.apache.velocity.app.VelocityEngine;

Import Org.apache.velocity.Template;

Import Org.apache.velocity.VelocityContext;

public class HelloWorld

{

public static void Main (string[] args)

Throws Exception

{

/* First, 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", "http://www.eiffelqiu.com");

/* 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, the result is:

Hello Eiffel qiu! Welcome to http://www.eiffelqiu.com World

To ensure smooth operation, load velocity's running package from Velocity's website http://jakarta.apache.org/velocity/ and place the path of the velocity Jar package in the system's Classpath, so that you can compile and run the above program.

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

Here Velocity gets the template file and gets 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", "http://www.eiffelqiu.com"), other code is fixed, but very important, but it is the same for each application:

This is the Initialize Velocity template engine

/* First, get and initialize an engine */

Velocityengine ve = new Velocityengine ();

Ve.init (); This is used to combine the environment variable with the output part.

StringWriter writer = new StringWriter ();

T.merge (context, writer);

/* Show the world * *

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

Well, let me summarize how Velocity really works :

Velocity solves the problem of how to pass data between Servlets and Web pages, of course, the mechanism for transmitting data is in the MVC pattern, that is, view and Modle, the Controller works independently of each other, and the modification of one party does not affect the change of other parties. environment variable (context) to achieve, of course, both sides of the Web page production side and background program to each other to agree on the naming convention of the passed variables, such as the last program example site, name variable, they are on the Web page is $name, $site. So as 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 does not change, then the background program does not need to change, the front page can be arbitrarily modified by the page maker. That's how Velocity works.

You will find that simple variable names often do not meet the needs of Web page production display data, such as we often loop to display some data sets, or based on some data values to determine how to display the next data, Velocity also provides a loop, the simple syntax to judge to meet the needs of web production. Velocity provides a simple template language for front-end Web page makers to use, and the template language is simple enough (most people who know JavaScript can quickly master it much simpler than JavaScript), and of course, this simple is deliberate, Because it does not need it to do anything, the View layer should not contain more logic, Velocity's simple template syntax can meet all of your page display logic needs, this is usually enough, there will not be a JSP as a result of an infinite loop statement to destroy the system, JSP Can do a lot of things, Sun in the development of the JSP 1.0 standard, there is no time to limit the programmer in the JSP insert code logic, so that the early JSP code more like PHP code, although powerful, but for the display layer of logic is not necessary, and will make the logical structure of the MVC three layer 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: 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.