Velocity First Experience

Source: Internet
Author: User
Tags foreach date end variables string version variable tostring

Many people have seen or learned velocity, the name literal translation: speed, rate, rapid, used in web development, the use of people may not be many, most of the basic know and in the use of struts, in the end velocity and struts how to contact, how to see velocity? Let's try it out, to understand the concept of velocity, through the introduction here, highlighting the problem in the choice of technology, so that everyone in the selection of project development, you can consider velocity, but also let everyone understand its thinking, after all, it provides a good way of thinking, for everyone to change bones, In a different way of thinking.

This article based on your Java development has a certain basis, know mvc,struts and other development models.

Velocity is a Java template engine technology that is proposed by Apache and is led by another engine technology webmacro. So what is the official velocity definition? Apache defines it as a java-based template engine, but allows anyone to use a simple and powerful template language to refer to objects defined in Java code. The latest version is 1.4, and you can find more information in http://jakarta.apache.org/velocity/index.html .

As a matter of fact, velocity is an implementation of the MVC architecture, but it is more concerned with model and view as a bridge between them. For the most popular architecture of MVC, struts, I believe everyone is familiar, many developers have been heavily in the use of struts architecture, including IBM's WebSphere more than 5 of the management platform version, Struts technology is a good practice of MVC, It effectively reduces the Java code in view (JSP) in the presence of, but between model and view or rely on struts taglib technology to achieve, just imagine if the foreground development of the web designer to struts and even taglib not familiar (I believe it is also very difficult to mature, Including later maintenance personnel as well), will be the web designer and the foreground development Engineer's mutual cooperation development brings the very big difficulty, the reality development also exists such fact, the webpage designer and the foreground development between the work more or less still has certain coupling, how to solve this problem maximally? Let's take a look at velocity or that concept.

Let's start with the simplest velocity development example to show how velocity works:

1, create 1 files, the file name is: HELLOVELOCITY.VM, that is, the velocity template (in fact, and HTML), content:

<title>hello velocity</title>

<body>

Welcome $name to javayou.com!

This is $date.

</body>

2, create 1 Java files, Hellovelocity.java, content:

Package com.javayou.velocity;

Import Java.io.StringWriter;

Import java.util.*;

Import Org.apache.velocity.app.VelocityEngine;

Import Org.apache.velocity.Template;

Import Org.apache.velocity.VelocityContext;

/**

* @author LIANG.XF 2004-12-14

*/

public class Hellovelocity {

public static void Main (string[] args) throws Exception {

Initialize and get velocity engine

Velocityengine ve = new Velocityengine ();

Ve.init ();

Get velocity of the template

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

Get the context of velocity

Velocitycontext context = new Velocitycontext ();

Fill in the context of the data

Context.put ("name", "Liang");

Context.put ("Date", (new Date ()). ToString ());

For the display in the back, enter the list value in advance

List temp = new ArrayList ();

Temp.add ("1");

Temp.add ("2");

Context.put ("list", temp);

Output stream

StringWriter writer = new StringWriter ();

Transformation output

T.merge (context, writer);

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

}

}

3. Load velocity 1.4 zip on http://jakarta.apache.org/site/binindex.cgi Extract the Velocity-1.4.jar after decompression, and use it to compile the class Hellovelocity.java above.

4, the 1 on the HELLOVELOCITY.VM copy to run the current directory, run hellovelocity also need other types of bags, can be downloaded from the Velocity1.4.zip, \\velocity-1.4\\build\\lib, The Commons-collections.jar and Logkit-1.0.1.jar are introduced and then run JAVA-CP. \\bin; -DJAVA.EXT.DIRS=.\\LIB2 Com.javayou.velocity.HelloVelocity, assuming class is compiled into the. \\bin directory, and the class package we need is placed in the. \\lib2 directory, and the running structure is as follows:

<title>hello velocity</title>

<body>

Welcome Liang to javayou.com!

This is Tue Dec 19:26:37 CST 2004.

</body>

The above is the simplest run result, how, know a probably, template HELLOVELOCITY.VM 2 define variable $name and $date are context.put respectively ("name", "Liang") and Context.put ("date", (New Date ()). ToString ()) replaces the value set by the.

It seems that business process processing, including business results are basically in the model of the whole solution, and view this layer is basically only using a simple VTL (Velocity Template Language) to show. So, JSP is not it? Yes, the usage pattern is a bit like the earlier CGI: the velocity automatically outputs the code, and velocity is very powerful in this way, and velocity is used to generate a lot of code in turbine.

In velocity, the definition of a variable starts with "$" and is used as an identifier for velocity. Letters, numbers, dashes, and underscores can be used as variable velocity definitions.

In addition, we need to pay attention to the velocity characteristics of the variable definition, such as: $student. No, $student. Address, it has 2 levels of meaning: The 1th is if student is Hashtable, then will be extracted from the Hashtable key is no and address the value, the other 2nd is that it is possible to call the method, That is, the above 2 variables will be converted to Student.getno () and student.getaddress (). Velocity has an object for the value returned by Java code in the servlet, and it can invoke the object's methods, such as $ student.getaddress (), and so on, where it is not an example and depth.

The example above is just a simple example, now of course many people have not satisfied with such an example, the actual application we also often need to do some selective presentation and enumeration of some iterative data, such as list, of course velocity (specifically, the VTL template language) also support this feature, There are other common displays, such as variables within the template (such as variables in the JSP), and powerful things like creating macros to automate, so let's go ahead and look.

Let's use the example above to change the contents of the template HELLOVELOCITY.VM to:

#set ($iAmVariable = "good!")

Welcome $name to javayou.com!

This is $date.

$iAmVariable

Re-execute the above Run command, and the result:

Welcome Liang to javayou.com!

This is Tue Dec 22:44:39 CST 2004.

good!

It is not difficult to understand that the variable in the template is defined as the statement at the beginning of the # set, and the variable $iamvariable in the following template is converted to the defined value: good!

Let's take a look at the simple option to change the contents of the template HELLOVELOCITY.VM to:

#set ($admin = "admin")

#set ($user = "user")

#if ($admin = = $user)

Welcome admin!

#else

Welcome user!

#end

Execute Run command, result:

Welcome user!

You can see that the judgment statement is simply #if (), #else, #end, not very complicated.

Then go ahead and look at the iteration data, and change the contents of the template HELLOVELOCITY.VM to:

#foreach ($product in $list)

<li> $product </li>

#end

Execute Run command, result:

<li>1</li>

<li>2</li>

Is it convenient to enumerate the values in the Velocitycontext list stored in the example? Just use #foreach ($variable in xx), if the list above is replaced by Hashtable, you can use the following syntax:

#foreach ($key in $hashVariable. Keyset ())

<li> $key ' s value: $ hashvariable.get ($key) </li>

#end

I don't think these scripts are complicated.

And a lot of people will ask, if it is javabean how to do? OK, let's add a bean:

Package com.javayou.velocity;

/**

* @author LIANG.XF 2004-12-14

*/

public class Student {

Note that the attribute of class is public.

Public String no = "";

Public String address = "";

Public Student (String _no, String _address) {

no = _no;

address = _address;

}

Public String getaddress () {

return address;

}

public void setaddress (String address) {

this.address = address;

}

Public String Getno () {

return no;

}

public void Setno (String no) {

this.no = no;

}

}

This student is a chronological javabean, or data bean, a common class used to load data, and then we modify the Hellovelocity.java to:

Temp.add ("1");

Temp.add ("2");

Replace with:

Temp.add (New Student ("123", "Guangzhou"));

Temp.add (New Student ("456", "Zhuhai"));

The contents of the HELLOVELOCITY.VM should be changed to:

#foreach ($s in $students)

< $velocityCount > Address: $s. Address

#end

Recompile and execute the Run command with the following result:

<1> Address:guangzhou

<2> Address:zhuhai

This is the list of student data printed out, done! This uses velocity's built-in variable $velocitycount, which refers to the default enumeration number, starting at 1, or changing to 0. However, it needs to be changed in Velocity.properties, Velocity.properties is located under the directory Org\\apache\\velocity\\runtime\\defaults in the Velocity-1.4.jar package.

How to deal with some more complicated iterations? Let's take a look at the following template examples to make it clear:

#foreach ($element in $list)

--Inner foreach--

#foreach ($element in $list)

This is $element.

$velocityCount

#end

--Inner foreach--

--Outer foreach--

This is $element.

$velocityCount

--Outer foreach--

#end

See, Velocity is the support tag nesting, this is very powerful function, here is not in-depth demo, if interested, try it yourself.

In fact, a little more in-depth thinking about the examples we have just given, we can already see that the use of velocity is where? The servlet + velocity pattern, and remember our early JSP development pattern Jsp+javabean? Here, we change to servlet+javabean+velocity, think about whether it has replaced Jsp+javabean, and more thoroughly remove Java code from the JSP (VM), if the light uses struts (servlet+jsp), The cost is that the Java code is always more or less on the JSP, even if you can do without Java code, but developers who have done complex architectural systems know that the costs are expensive, and that there are some difficulties in maintainability and in the integration development of web designers, so here we feel, The Servlet+javabean+velocity model achieves the concept of Ood well. In terms of efficiency, there is no need to worry that this combination is more efficient than the servlet+jsp approach.

Willing to understand the velocity of people should be a lot, but really practical to the project, perhaps not much (or some items in use, such as jute), after all, and JSP compared to JSP more standard, more widely used and many development tools have been supporting JSP development. But the velocity of the function is not only limited to the competition with JSP, from the above can be seen in the output of automatic code is very strong, mentioned turbine is to use velocity to generate a lot of code, you can make a little change can be made into a code generator, or other template generation, are very good ideas.

Well, let's take a look at some of the common problems that need to be noticed when we dive into velocity to do projects, first of all, internationalization,

Velocity itself supports the internationalization coding transformation of the template, looking at velocity-provided methods:

Public Template gettemplate (stirng Template, String encoding),

It is speculated that this does not really internationalize.

The simplest concept of internationalization in struts, that is, the use of international language tags in the JSP to do, and each language using a different language tag library way, extended to here, in fact, hand to do as can be done, but need a little manual processing.

Fortunately, someone has already dealt with the above question, made the velocity of the tools:messagetool, provided the variable text contains the internationalization of tags, so you need to simply write the tag code, such as: $text. Get (' title '), More specific content can also be understood in the http://jakarta.apache.org/velocity/tools/struts/MessageTool.html .

Well, let's say so much about the velocity, and then we'll talk about other extensions. Some people commented that velocity is not a standard MVC structure, yes, at first we said Velocity is just a good combination of model and view, but a good template engine, after all, has not formed a good combination of MVC. Fortunately, Apache is also based on the combination of struts and velocity, the introduction of the Velocitystruts, this part of the statement we can be introduced in the later topic, here a brief introduction to its concept, it is in the structure of struts, in the business logic after the action, Shift the business process to a velocity based display layer, replacing the JSP as the view layer. We've also seen that the examples given are basically based on principles and demos, not closely linked to web development, and we'll combine them when we're talking about velocitystruts content.

When it comes to velocity, here's to mention that Freemarker,freemarker is also a template engine, which is basically similar to velocity, and is a simple and lightweight tool, but has a much stronger function than velocity. This we also in the future article to further understand it.



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.