Velocity, literally translated as: speed, speed, and speed, used in web development, there may not be many people who have used it, most of them basically know and are using struts, in the end, how does velocity and Struts (taglib and tiles) contact? In terms of technology, velocity is more advanced than struts (taglib and tiles). velocity can be considered technically. Struts is widely used and there are many such talents, therefore, it is easy for companies to select struts talents. After all, velocity provides a good way of thinking.
Velocity is a Java template engine technology. This project was proposed by Apache and is deeply introduced by another engine technology webmacro. So what is the official definition of velocity? Apache defines it as a Java-based template engine, but allows anyone to use a simple and powerful template language to reference the definition in JavaCode. The latest version is 1.4. You can find more information at http://jakarta.apache.org/velocity/index.html.
In fact, velocity is an implementation of the MVC Architecture, but it focuses more on the relationship between model and view as a bridge between them. For the most popular MVC Architecture struts, I believe everyone is familiar with it. Many developers are already using the struts architecture, including the Management Platform version of IBM WebSphere 5 or above, struts is a good practice of MVC, which effectively reduces the appearance of Java code in view (JSP). However, the taglib Technology of Struts is used between model and view, imagine if the front-end web designers are not familiar with Struts or even taglib (I believe they are quite familiar with it, including the later maintenance personnel ), this will make it very difficult for web designers and front-end development engineers to collaborate with each other for development. In reality, such a fact still exists in development, the work between web designers and front-end developers is more or less coupled. How can we solve this problem to the maximum extent? Let's take a look at velocity or this concept.
Below is a simple velocity example:
1. Create a velocity template (in fact, the same as HTML). The file name is hellovelocity. VM.
<HTML>
<Title> Hello velocity </title>
<Body>
Welcome $ name to javayou.com!
Today is $ date.
</Body>
</Html>
2. Create a 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 obtain the velocity Engine
Velocityengine VE = new velocityengine ();
Ve. INIT ();
// Obtain the velocity Template
Template T = VE. gettemplate ("hellovelocity. VM ");
// Obtain the context of Velocity
Velocitycontext context = new velocitycontext ();
// Enter the data in the context
Context. Put ("name", "Liang ");
Context. Put ("date", (new date (). tostring ());
// For the subsequent 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. Copy hellovelocity. VM on 1 to the current directory. The running structure is as follows:
<HTML>
<Title> Hello velocity </title>
<Body>
Welcome Liang to javayou.com!
Today is Tue dec 14 19:26:37 CST 2004.
</Body>
</Html>
The above is the simplest running result. How about it? The template hellovelocity. the two definition variables $ name and $ date in the VM are context. put ("name", "Liang") and context. put ("date", (new date ()). the value of tostring () is replaced.
From this point of view, the Business Process processing includes the basic solution of the business results on the model layer, while the view layer is basically presented using a simple VTL (velocity template language. In this case, isn't JSP unnecessary? Yes, this usage mode is a bit like the previous CGI method: the code is automatically output by velocity, and velocity has a strong capability in this aspect. In turbine, velocity is used to generate a lot of code.
In velocity, variable definitions start with "$" and $ is the identifier of velocity. Letters, numbers, hyphens, and underscores can all be Defined variables of velocity.
It is also worth noting that velocity features variable definitions, such as $ student. No and $ student. Address, which have two meanings:
LIf student is hashtable, the value of key no and address will be extracted from hashtable,
LThe other 2nd variables may be called methods, 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 object methods, such as $ student. getaddress (). Here we will not give an example or go deeper.
The above example is just a simple example. Now, of course many people are not satisfied with this example. In actual applications, we often need to selectively present and list some iterative data, for example, the list, of course, velocity (which should be VTL template language) also supports this function, and also supports some other commonly used presentations, for example, the variables inside the template (such as the variables in JSP), and the powerful ones such as the Creation macro to achieve automation, let's continue to look at it.
We still use the above example to change the content in the template hellovelocity. VM:
# Set ($ iamvariable = "Good! ")
Welcome $ name to csdn.net!
Today is $ date.
$ Iamvariable
Run the preceding command again. The result is:
Welcome Liang to csdn.net!
Today is Tue dec 14 22:44:39 CST 2004.
Good!
It can be seen that the variable in the template is defined as the statement starting with # set, which is not difficult to understand. After execution, the variable $ iamvariable in the template is converted to the defined value: Good!
Let's take a look at the simple selection and change the content in the hellovelocity. VM template:
# Set ($ admin = "admin ")
# Set ($ user = "user ")
# If ($ admin = $ user)
Welcome admin!
# Else
Welcome user!
# End
Run the following command:
Welcome user!
We can see that the judgment statement is simple: # If (), # else, # End, not very complex.
Next, let's take a look at the iterative data and change the content in the hellovelocity. VM template:
# Foreach ($ product in $ List)
<Li> $ product </LI>
# End
Run the following command:
<Li> 1 </LI>
<Li> 2 </LI>
In this example, the values in the list with the pre-saved velocitycontext are listed. Is it very convenient? Only # foreach ($ variable in XX) is used. If the list above is changed to 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 at all.
Some people may ask, what if it is a JavaBean? Okay, let's add a bean:
Package com. fasttalk. velocity;
Public class student {
// Note that the class attribute 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 real JavaBean, or data Bean, a common class used to load data. Then we modify hellovelocity. Java:
Temp. Add ("1 ");
Temp. Add ("2 ");
Replace:
Temp. Add (new student ("123 "," Guangzhou "));
Temp. Add (new student ("456", "Zhuhai "));
Change hellovelocity. VM:
# Foreach ($ s in $ students)
<$ Velocitycount> address: $ S. Address
# End
Recompile and run the command. The result is as follows:
<1> address: Guangzhou
<2> address: Zhuhai
Print the student data in the list! Here, the built-in variable $ velocitycount of velocity is used, which refers to the default list number. It can be changed from 1 to 0, but must be in velocity. properties, velocity. properties is located under ORG/Apache/velocity/runtime/defaults, directory in the velocity-1.4.jar package.
How to deal with complicated iterations? Let's take a look at the following template example to get 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 label nesting. This is a very powerful function and will not be further demonstrated here. If you are interested, try it yourself.
As a matter of fact, we can see from the previous example where velocity is used? That is, Servlet + velocity mode. In addition, do you still remember the JSP + JavaBean mode we developed in the early days? Here, we change it to servlet + JavaBean + velocity. Think about whether JSP + JavaBean has been replaced and Java code has been completely removed from JSP (VM, if struts (servlet + JSP) is used, the cost is that Java code always appears on JSP, even if Java code is not displayed, however, developers who have worked on complex architecture systems know that the cost is very expensive and there are some difficulties in Maintainability and integrated development with web designers. Therefore, we can feel that, servlet + JavaBean + velocity mode better implements the concept of Ood. In terms of efficiency, you don't have to worry about it. This combination method is more efficient than servlet + JSP.
There should be a lot of people willing to know about velocity, but there may not be many practical projects (or some projects are in use, such as jute). After all, compared with JSP, JSP is more standard, more widely used, and many development tools have supported JSP development. However, the velocity function is not limited to competition with JSP. It can be seen that it is very powerful in Automatic Code output. As mentioned above, turbine uses velocity to generate a lot of code, you can also make code generators or generate other templates with slight changes. This is a good idea.
Now, let's take a look at some common problems that need to be paid attention to when going deep into the velocity project. The first is the internationalization problem,
Velocity itself supports international Transcoding of templates. Let's take a look at the methods provided by velocity:
Public template gettemplate (stirng template, string encoding ),
It is inferred that such operations cannot be completely internationalized.
The simplest concept of internationalization in struts is to use the international language tag on JSP, and each language uses a different language tag library, in fact, you can do the same by hand, but you only need a little manual processing.
Fortunately, someone has already handled the problem mentioned above and made it into velocity tools: messagetool. The variable text contains the internationalized tag, so you only need to write the tag code, for example: $ text. get ('title'), more details can also be learned in http://jakarta.apache.org/velocity/tools/struts/MessageTool.html.
Well, we can say so much based on the introduction of velocity. Let's talk about other extensions. Some people commented that velocity is not a standard MVC structure. That's right. At the beginning, we said that velocity is only a good combination between model and view, but a good template engine, after all, there is no good combination of MVC. Fortunately, Apache launched velocitystruts based on the combination of struts and velocity. We can introduce this part of the statement in the subsequent topics. Here we will briefly introduce its concept, it is based on the struts structure. After the action processed by the business logic, the business flow is switched to the display Layer Based on velocity, replacing JSP as the view layer. We have also seen that the example is basically based on the principle and demonstration, and is not closely integrated with web development. In this regard, let's talk about the content of velocitystruts.
Speaking of velocity, freemarker should be mentioned here. freemarker is also a template engine. It is similar to the velocity function and is both a simple and lightweight tool, however, there are a lot of enhancements to the velocity feature, which we will alsoArticleTo learn more.