Many people have seen or learned about Velocity. The literal translation of the name is: speed, speed, rapidity. It is used in web development, but not many people have used it. Most of them basically know and use Struts. How are Velocity and Struts related? , what do you think of Velocity? Let us give it a try and understand the concept of Velocity. Through the introduction here, we emphasize the issues in technology selection, so that everyone can consider Velocity when choosing project development, and also let everyone understand its ideas. After all, it provides A very good way of thinking, giving everyone a change of heart and a different way of thinking.
This article is based on the fact that you have a certain foundation in Java development and know MVC, Struts and other development models.
Velocity is a Java template engine technology. The project was proposed by Apache and was derived from another engine technology, Webmacro. So what is the official definition of Velocity? Apache defines it as: a template engine based on Java, but allows anyone to use a simple and powerful template language to reference objects defined in Java code. The latest version is 1.4. You can find more information at http://jakarta.apache.org/velocity/index.html .
In fact, to put it bluntly, Velocity is an implementation of the MVC architecture, but it focuses more on the relationship between Model and View as a bridge between them. I believe everyone is familiar with Struts, the most popular architecture of MVC. Many developers have been using the Struts architecture extensively, including management platform versions of IBM's Websphere 5 or above. Struts technology is a good practice of MVC, and it effectively reduces Java code appears in View (Jsp), but the connection between Model and View still relies on Struts’ Taglib technology. Just imagine if the front-end web designer is not familiar with Struts or even Taglib (I believe it is quite difficult to be familiar with it, including The same goes for later maintenance personnel), which will make it very difficult for web designers and front-end development engineers to cooperate with each other. In real development, there is still such a fact that the work between web designers and front-end developers may be more complicated. There is still a certain degree of coupling. How to solve this problem to the greatest extent? Let's take a look at Velocity or this concept.
Let’s start with the simplest Velocity development example to show you how Velocity works:
1. Create a file, the file name is: hellavelocity.vm, which is the velocity template (actually the same as html), the content is:
Welcome $name to Javayou.com!
today is $date.
2. Create a java file, HelloVelocity.java, with 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 obtain the Velocity engine
VelocityEngine ve = new VelocityEngine();
ve.init();
//Get the velocity template
Template t = ve.getTemplate("hellovelocity.vm");
//Get the context of velocity
VelocityContext context = new VelocityContext();
//Fill data into context
context.put("name", "Liang");
context.put("date", (new Date()).toString());
//For later 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();
//convert output
t.merge(context, writer);
System.out.println(writer.toString());
}
}
3. Download the Velocity 1.4 zip at http://jakarta.apache.org/site/binindex.cgi , unzip it to get velocity-1.4.jar, and use it to compile the above class HelloVelocity.java.
4. Copy hellavelocity.vm on 1 to the current directory of the run. Running HelloVelocity also requires other packages, which can be obtained from the downloaded velocity1.4.zip, \velocity - 1.4\build\lib, and put After commons-collections.jar and logkit-1.0.1.jar are introduced, run java -cp .\bin; -Djava.ext.dirs=.\lib2 com.javayou.velocity.HelloVelocity, assuming the class is compiled to .\ bin directory, and the class packages we need are placed in the .\lib2 directory. The running structure is as follows:
Welcome Liang to Javayou.com!
today is Tue Dec 14 19:26:37 CST 2004.
The above is the simplest running result. How about it? Let me know roughly. The two defined variables $name and $date in the hellavelocity.vm template are respectively context.put("name", "Liang") and context.put( "date", (new Date()).toString()) is replaced by the value set.
From this point of view, business process processing, including business results, is basically all solved at the model layer, while the view layer is basically only displayed using a simple VTL (Velocity Template Language). In this way, wouldn't Jsp be unnecessary? Yes, this usage model is a bit like the earlier CGI method:) Velocity automatically outputs code, and Velocity is also very capable in this regard. Velocity is used in Turbine to generate a lot of code.
In Velocity, variable definitions start with "$", and $ serves as the identifier of Velocity. Letters, numbers, strokes, and underlines can all be used as defined variables in Velocity.
In addition, we also need to pay attention to Velocity's characteristic variable definitions, such as: $student.No, $student.Address, which have two levels of meaning: the first is if the student is a hashtable, the key No and will be extracted from the hashtable The value of Address, and the second type is that it may be a calling method, that is, the above two variables will be converted to student.getNo() and student.getAddress(). Velocity has an object for the value returned by the java code in the servlet, and can also call the object's methods, such as $student.getAddress(), etc. I will not give examples and go into detail here.
The above example is just a simple example. Of course, many people are no longer satisfied with such examples. In actual applications, we often need to make some selective displays and enumerate some iterative data, such as List lists, and of course Velocity (specifically It should be VTL template language) also supports this function. In addition, it also supports some other commonly used displays, such as variables inside the template (such as variables in Jsp), and more powerful ones such as creating macros to achieve automation. Let us continue. Read on.
We still use the above example and change the content in the hellavelocity.vm template to:
#set( $iAmVariable = "good!" )
Welcome $name to Javayou.com!
today is $date.
$iAmVariable
Re-execute the above run command, the result is:
Welcome Liang to Javayou.com!
today is Tue Dec 14 22:44:39 CST 2004.
good!
You can see that the variables in the template are defined as statements starting with #set, which is not difficult to understand. After execution, the variables $iAmVariable in the template are converted to the defined values:
good!
Let's look at a simple choice again. Change the content in the hellavelocity.vm template to:
#set ($admin = "admin")
#set ($user = "user")
#if ($admin == $user)
Welcome admin!
#else
Welcome user!
#end
Execute the run command, the result is:
Welcome user!
You can see that the judgment statements are just simple #if (), #else, #end, not very complicated.
Let’s continue to look at the iteration data and change the content in the template hellavelocity.vm to:
#foreach( $product in $list )
$product
#end
Execute the run command, the result is:
#1
#2
Isn’t it convenient to list the values pre-saved in the VelocityContext List in the example? Just use #foreach ($variable in xx). If the above List is replaced with a Hashtable, you can use the following syntax:
#foreach($key in $hashVariable.keySet() )
$key 's value: $ hashVariable.get($key)
#end
I don't think these scripts are complicated at all.
Many people will also ask, what if it is javabean? Okay, let's add a bean:
package com.javayou.velocity;
/**
* @author Liang.xf 2004-12-14
*/
public class Student {
//Note that the attributes 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 a full javabean, or data bean, a common class used to load data. Then we modify 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 hellavelocity.vm to:
#foreach ($s in $students)
<$velocityCount> Address: $s.address
#end
Recompile and execute the run command, the results are as follows:
<1> Address: Guangzhou
<2> Address: Zhuhai
In this way, the Student data in the list is printed out, and you're done! Velocity's built-in variable $velocityCount is used here, which refers to the default enumeration sequence number. It starts from 1. It can also be changed to 0, but it needs to be changed in Velocity.properties. Velocity.properties is located in the velocity-1.4.jar package. Under the directory org\apache\velocity \runtime\defaults .
How to deal with more complex iterations? Let’s look at the following template example 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
As you can see, Velocity supports tag nesting. This is a very powerful function. I won’t demonstrate it in depth here. If you are interested, try it yourself.
In fact, if you think about the example we just gave a little more in-depth, you can already see, what is the use of Velocity? That is the Servlet + Velocity model. In addition, do you still remember our early Jsp development model Jsp+JavaBean? Here, we changed to Servlet+JavaBean+Velocity. Think about it, has it replaced Jsp+JavaBean, and more thoroughly removed the Java code from Jsp (vm). If you only use Struts (Servlet+Jsp), then The cost is that Java code always appears more or less in JSP. Even if it can be done without Java code, developers who have done complex architecture systems know that the cost is also very expensive, and in terms of maintainability, There are certain difficulties in integrated development with web designers, so we can feel here that the Servlet+JavaBean+Velocity model better realizes the concept of OOD. In terms of efficiency, you don't have to worry. This combination is more efficient than the Servlet+Jsp method.
There should be many people who are willing to learn about Velocity, but perhaps not many can actually apply it to projects (some projects still use it, such as Jute). After all, compared with Jsp, Jsp is more standard and widely used, and many development tools have been used. Support Jsp development. But the function of Velocity is not limited to competition with Jsp. As can be seen from the above, it is very powerful in automatic code output. As mentioned earlier, Turbine uses Velocity to generate a lot of code. You can also make slight changes. It is a very good idea to make it into a code generator or other template generation.
Okay, let’s take a look at some common issues that need to be paid attention to if you want to go deep into Velocity to do projects. The first is the issue of internationalization.
Velocity itself supports international encoding conversion of templates. Take a look at the methods provided by Velocity:
Public Template getTemplate (Stirng template, String encoding),
It is speculated that this approach cannot achieve complete internationalization.
The simplest concept of internationalization in Struts is to use international language tags on Jsp, and each language uses a different language tag library. By extension, it can actually be done manually. Yes, it just requires a little bit of manual processing.
Fortunately, someone has already solved the problem mentioned above and created Velocity's tools: MessageTool, which provides the variable text to contain internationalized labels. In this way, you only need to simply write label code, such as: $text.get('title' ), more specific content can also be found at http://jakarta.apache.org/velocity/tools/struts/MessageTool.html .
Okay, that’s all based on the introduction of Velocity, let’s talk about other extensions. Some people commented that Velocity is not a standard MVC structure. Yes, we said at the beginning that Velocity is just a good combination between Model and View, and is just a good template engine. After all, a good combination of MVC has not yet been formed. Fortunately, Apache launched VelocityStruts based on the combination of Struts and Velocity. We can introduce this part of the statement in a later topic. Here is a brief introduction to its concept. It is based on the structure of Struts and the Action of business logic processing. Finally, the business process is shifted to the display layer based on Velocity, thereby replacing Jsp as the View layer. We have also seen above that the examples cited are basically based on principles and demonstrations, and are not closely integrated with Web development. We will combine this aspect when describing the content of VelocityStruts.
Introduction to using Velocity - code in java
1. First initialize the object
VelocityContext context = new VelocityContext();
StringWriter writer = new StringWriter();
String encoding2 = "GBK";
2. PROPERTY_PATH = TEMPLATE_INIT_PATH in the system properties file (Specify the property file path required for velocity.)
3. Contents in Properties
file.resource.loader.path = D:/resin/webapps/mip/files/templateupload/ (where the template is located)
4. Then initialize Velocity.init(PROPERTY_PATH);
5. Correspond the labels in velocity to java context.put(key, value);
6. Then load the file Velocity.mergeTemplate(templateName, encoding2, context, writer);
7. Finally, call Generator.writeToFile() to generate the file.
8. The writeToFile function is as follows:
FileOutputStream of = new FileOutputStream(theFile);
of.write(writer.toString().getBytes("GBK"));
// String tt = writer.toString();
of.flush();
of.close();
This article comes from the CSDN blog. Please indicate the source when reprinting: http://blog.csdn.net/sunrui_work/archive/2009/12/18/5029982.aspx