Velocity Template Engine Learning (1)

Source: Internet
Author: User

Velocity and Freemaker, jstl are called Java Web Development Three big label technology, and Velocity on the CodePlex also has. NET ported version nvelocity, (note: The Castle team also maintains a version on GitHub For teams that use heterogeneous technologies. NET and Java), always want to find a common technology, compatible with all technology platforms, in order to reduce the cost of learning, it is no doubt that velocity is a good choice to consider.

First, integration with the STRTUS2

1         <dependency> 2             <groupId>org.apache.velocity</groupId> 3             <artifactId> Velocity</artifactid> 4             <version>1.7</version> 5         </dependency> 6  7         < Dependency> 8             <groupId>org.apache.velocity</groupId> 9             <artifactid>velocity-tools </artifactid>10             <version>2.0</version>11         </dependency>

Pom.xml add these two items, others do not have to be deliberately configured. STRUTS2 supports both JSTL (. jsp), velocity (. vm), Freemaker (. FTL) Three templates.

Second, define the variable

1   #set ($awbpre = ' "") 2   #set ($awbno = ' 89089011 ') 3   #set ($airwayBillNo = $awbpre + '-' + $awbno) 4   $ awbpre-$awbno <br/>5   $airwayBillNo

Velocity's grammatical notation is about two classes, one with #, a control symbol, a #set表示定义变量, and another with $, usually for displaying variables, and the above example defines three variables:
The Awbpre value is ' awbno ', the value is ' 89089011 ' and the Airwaybillno value is ' 112-89089011 '

4th, 52 Line output content

Third, iterating through the array

1   #set ($list = ["CTU", "SHA", "LAX"]) 2   #foreach ($item in $list) 3      $velocityCount. $item <br/>4   # End

Explanation: An array is defined, and then the output is traversed, where Velocitycount is the index variable

Iv. Traversal of Hashtable

1   #foreach ($key in $table. KeySet ()) 2     $key, $table. Get ($key) <br/>3   #end


V. Determine if the set is empty

1       #if ($null. IsNull (erList. Orders) | | erList. orders.size () ==0) 2           order list is empty 3       #else4           order list:< Br/>5           #foreach (er in erList. Orders) 6               $velocityCount: er. ID/er. clientname/er. Amount /er. createtime<br/>7           #end8       #end


Vi. Examples of macros

Macros can be understood as "functions", and defining a macro is equivalent to defining a child function, calling a macro, calling a child function

1     #macro (renderorderlist ers) 2         <table border= "1" > 3           <tr> 4               <th>Id</th> 5               <th>ClientName</th> 6               <th>Amount</th> 7               <th>CreateTime</th> 8           </tr> 9           #foreach ($o in ers)             <tr><td> $o .id</td><td> $o. clientName </td><td> $o .amount</td><td> $o. createtime</td></tr>11           #end12         < /table>13     #end14     #renderOrderList (erList orders)


Seven, numeric, date formatting

1     er. createtime<br/>2     $date. year-$date. month-$date. Day <br/>3     $date. Format (' Yyyy-mm-dd HH:mm:ss ', er. Createtime, $locale) <br/>  4     $date. Format (' Mmmdd ', er. createtime,$ Locale) <br/>    5     $convert. Tolocale ("en_US") <br/>6     $date. Format (' Mmm,dd ', $ Order.createtime, $convert. Tolocale ("en_US")) <br/>7     $date. Format (' Yyyy-mm-dd ', er. createtime,$ Locale) <br/>8     er. amount<br/>9     . Format (' 0.00 ', er. Amount) <br/>

To use the formatting feature, add a bit of configuration, add a line to the Struts.xml file

<constant name= "struts.velocity.toolboxlocation" value= "Web-inf/classes/toolbox.xml"/>

Then, in Toolbox.xml, refer to the following:

View Code

These xxxtool are actually a good example, because the velocity of the VM file can not directly write Java code, if we want to extend some common methods, you can write some common methods Xxxtool tool class, and then register in Toolbox.

Viii. Internationalization

1  current locale: $locale <br/>   2  #stext ("Name=%{gettext (' AppName ')}")

Although Velocity-tools 2.0 provided the Messagetool, but I have not tried to succeed, only with the use of the struts2 itself to deal with the label. The basename of internationalized resource files must be defined first in STRUTS2

1 <constant name= "struts.custom.i18n.resources" value= "message" ></constant>

Then in the Classpath directory, put two files message_zh_cn.properties, message_en_us.properties, inside put a appname=xxx content, with #stext can take the international content

Ix. Use of Struts2 tags

Although the velocity can basically say goodbye to Struts2 's pile of tags, but if you miss Struts2 in the label, you can continue to use, method: "#s" start on the line, refer to the following example:

1 #stextarea ("label=biography" "Name=bio" "cols=20" "rows=3") <br/>2 #sselect ("Label=favourite Color" "list={" Red ', ' Blue ', ' Green '} ' "Name=favouritecolor" "Emptyoption=true" "Headerkey=none" "Headervalue=none")    

X. Built-in objects

1 $request <br/>2 name = $request. GetParameter ("name") <br/>3 $session <br/>

Velocity can directly use many of Struts2 's built-in objects, such as request, Session, Response, and the example above shows how to get URL request parameters

Xi. include, parse to implement the layout of the modular

For each page, there will usually be some common headers and tails that can be included with include or parse to include other VM files (or txt/html files), the two difference being that include simply imports other files and does not perform any parsing of the VM syntax. When parse imports other VM files, parse parses execution if there are instructions in other VM files, such as defining variables, defining macros, and so on.

1 #parse ("TEMPLATE/HEADER.VM") 2 #include ("TEMPLATE/FOOTER.VM")

About the loading path, here to explain, the official document is not clear, velocity supports two path loading mechanism, press CLASSPATH or press filepath, by default, by Classpath path loading, that is: As long as the included. vm Files in/ Web-inf/classes directory. The above example, will be in the/web-inf/classes/template directory, search HEADER.VM, FOOTER.VM These two files, if found on the load, otherwise an error.

Finally talk about the IDE to. VM Visual support issues, currently on the latest eclipse, no easy to use plug-ins (Googlecode on the most of the plug-in is no longer maintained, and the latest eclipse incompatible), it is recommended that IntelliJ idea, It supports a better visualization of the VM.

For more detailed usage, please refer to the following legal documents:

Velocity Engine User Guide

Velocity Engine Developer's Guide

Velocity Tools Usage Overview

Velocity Template Engine Learning (1)

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.