MVC Framework Display Layer--velocity technology

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/fasttalk/article/details/398059

Velocity, the name literally translated as: speed, velocity, rapid, used in web development, used by people may not be many, most basic know and in use struts, exactly how velocity and struts (taglib and tiles) how to contact? Technically, the velocity is more advanced than struts struts (taglib and tiles), and it is technically possible to think about velocity, and struts is a very common and talented person, so it's easy for companies to choose Struts. After all, velocity provides a good way to think, to change a way of thinking.

Velocity is a Java template engine technology, proposed by Apache and Webmacro by another engine technology. What is the official velocity definition? Apache defines it as a Java-based template engine, but allows anyone to reference objects defined in Java code using a simple and powerful template language. Currently the latest version is 1.4 and can find more information in http://jakarta.apache.org/velocity/index.html.

Velocity, in fact, is an implementation of the MVC architecture, but it's more about being a bridge between model and view. For the most popular architecture of MVC, struts, I believe everyone is not unfamiliar, many developers are already using the struts architecture, including IBM's WebSphere 5 management platform version, Struts technology very good practice of MVC, It effectively reduces the appearance of Java code in the View (JSP), but between the model and view or rely on struts taglib technology to achieve, imagine if the front-page developers of web designers to struts and even taglib do not know (believe also very difficult to mature, Including the post-maintenance staff is the same), will be the web designer and front-end development engineers to develop the collaborative development of a great difficulty, the reality of development is still there is such a fact, the work of web designers and front-end development of more or less there is a certain coupling, how to maximize the solution of this problem? Let's take a look at velocity or that concept.

The following is a simple velocity example:

1, create the velocity template (in fact, the same as HTML), the file name is: HELLOVELOCITY.VM

<title>hello velocity</title>
<body>
Welcome $name to javayou.com!
Today is $date.
</body>

2. Create Java file, Hellovelocity.java:

Package Com.fasttalk. Velocity
Import Java.io.StringWriter;
Import java.util.*;
Import Org.apache.velocity.app.VelocityEngine;
Import Org.apache.velocity.Template;
Import Org.apache.velocity.VelocityContext;

Public class Hellovelocity {
Public static void Main (string[] args) throws Exception {
//Initialize and get velocity engine
velocityengine ve = new Velocityengine ();
ve.init ();
//Get velocity's template
Template t = ve.gettemplate ("HELLOVELOCITY.VM");
//Get Velocity's contextual context
Velocitycontext context = new Velocitycontext ();
//Fill in the data in the context
context.put ("name", "Liang");
context.put ("Date", (new Date ()). ToString ());
//For the following display, 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 ();
//Conversion Output
T.merge (context, writer);
System.out.println (writer.tostring ());

}

Download Velocity 1.4 zip on http://jakarta.apache.org/site/binindex.cgi

4, the 1 HELLOVELOCITY.VM copy to run the current directory, run the following structure:

<title>hello velocity</title>
<body>
Welcome Liang to javayou.com!
Today is Tue Dec 19:26:37 CST 2004.
</body>

The above is the simplest running results, how, know about it, the template hellovelocity.vm in the 2 definition variables $name and the last three were Context.put ("name", "Liang") and Context.put ("date", The value set by (new Date ()). ToString ()) is substituted.

As a result, business process processing, including business results, is largely addressed in the model layer, and the view layer is simply presented using the simple VTL (Velocity Template Language). In this way, does JSP not use it? Yes, this usage pattern is a bit like the earlier CGI way: the velocity automatically outputs the code, and velocity is also very powerful in this area, and turbine uses velocity to generate a lot of code.

In velocity, the definition of a variable is the identifier for velocity, which begins with "$". Letters, numbers, strokes, and underscores can all be used as a defined variable for velocity.

It is also important to note the variable definition of the velocity feature, such as: $student. No, $student. Address, which has 2 levels of meaning:

The 1th is if the student is Hashtable, the value of the key no and address will be extracted from the Hashtable .

The other 2nd is that it is possible to invoke the method, that is, the above 2 variables will be converted to Student.getno () and student.getaddress ().

Velocity has objects in the values returned by Java code in the servlet, as well as methods to invoke the object, such as $ student.getaddress (), and so on, without example and in depth.

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

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

#set ($iAmVariable = "good!")
Welcome $name to csdn.net!
Today is $date.
$iAmVariable

Re-execute the above Run command, result:

Welcome Liang to csdn.net!
Today is Tue Dec 22:44:39 CST 2004.
good!

You can see that the variables in the template are defined as # set at the beginning of the statement, it is not difficult to understand, after the execution of the template variable $iamvariable are converted to the defined values: good!

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 just a simple # if (), #else, #end, not very complex.

Then go ahead and look at the iteration data to 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 list the values in the list that were pre-saved in the Velocitycontext in the example? Just use #foreach ($variable in xx) only, if the above list is replaced with Hashtable, then you can use the following syntax:

#foreach ($key in $hashVariable. KeySet ())
<li> $key ' s value: $ hashvariable.get ($key) </li>
#end

Don't think these scripts are complicated.

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

Package com.fasttalk.velocity;

public class Student {
Note that the properties of class are 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 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"));

Then change the contents of HELLOVELOCITY.VM to:

#foreach ($s in $students)
< $velocityCount > Address: $s. Address
#end

Recompile and execute the Run command with the following results:

<1> Address:guangzhou
<2> Address:zhuhai

So the list of student data printed out, done! Here is the velocity of the built-in variable $velocitycount, refers to the default enumeration ordinal, starting from 1, can also be changed to 0 start, But it needs to be changed in Velocity.properties, Velocity.properties is located under the directory Org/apache/velocity/runtime/defaults within the Velocity-1.4.jar package.

What about the more complicated iterations? Let's take a look at the template example below 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 a support tag nesting, this is a very powerful function, here is not in-depth demonstration, if interested, try it yourself.

In fact, a little more in-depth thinking about the example we have just given, we can see that the use of velocity is where? That is, the servlet + velocity mode, in addition, remember our early JSP development mode Jsp+javabean? Here, we change to servlet+javabean+velocity, think, is not already replaced Jsp+javabean, and more thoroughly remove Java code outside the JSP (VM), if the light uses struts (servlet+jsp), The cost is that Java code is always more or less on the JSP, even if the Java code can not appear, but the developers of the complex architecture system know that the cost is very expensive, and in the maintainability, and web designer integration development has some difficulties, so we can feel here, The Servlet+javabean+velocity model realizes the concept of Ood better. And in the efficiency, we do not have to worry, this kind of combination is more efficient than the way servlet+jsp.

People who are willing to understand velocity should be a lot, but really practical to the project, perhaps not many (or some projects in use, such as jute), after all, and JSP, JSP more standard, more widely used and a lot of development tools have supported JSP development. But the velocity of the function is not confined to the JSP competition with the situation, it can be seen in the automatic code output is very strong, the previous mentioned turbine is the use of velocity to generate a lot of code, you can make a little change can be made into code generator, or other template generation, is a very good idea.

Well, let's take a look at some of the frequently asked questions about getting to the velocity to do the project, first of all, internationalization,

Velocity itself supports the internationalization code conversion of the template to see how velocity provides:

Public Template gettemplate (stirng template, String encoding),

It is speculated that this can not be completely internationalized.

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

Fortunately, someone has already dealt with the above-mentioned problem, and made the velocity of the tools:messagetool, provided the variable text contains the internationalization tag, so only need to write a simple tag code, such as: $text. Get (' title '), More specific content is also available in the http://jakarta.apache.org/velocity/tools/struts/MessageTool.html.

Well, we're talking so much about velocity, so let's talk about other extensions. Some people commented that velocity is not a standard MVC structure, yes, we just started by saying that velocity is just a good combination of model and view, just a good template engine, after all, there is no good combination of MVC. Fortunately Apache, based on the combination of struts and velocity, introduced the velocitystruts, which we can introduce in the following topic, which is a brief introduction to its concept, which is in the structure of struts, after the action of business logic processing, Shift the business process to the velocity-based display layer instead of the JSP as the view layer. We also see that the examples given are basically based on principles and demonstrations, not in conjunction with web development, which we'll combine when we talk about velocitystruts content.

Speaking of velocity, here's to mention that Freemarker,freemarker is also a template engine, and the velocity function is basically similar, are simple and lightweight tools, but functionally more than the velocity has a lot of enhancements, We will also learn more about this in future articles.

MVC Framework Display Layer--velocity technology

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.