Use velocity templates in spring

Source: Internet
Author: User

Using the Velocity template

Velocity is an easy-to-use template language for Java applications. The velocity template does not have any Java code, which makes it easy for both non-developers and developers to understand. That's what Velocity's user manual says: "Velocity separates Java code from Web pages, makes it easier to maintain in the long run using a Web site, and provides a viable JavaServer pages alternative solution." ”

In addition to jsp,velocity, it may be the most popular template language for Web applications. So it's likely that you'll want to use velocity as a view-layer technology to develop spring-based applications. Fortunately, spring supports the use of velocity as the view-layer template language for spring MVC.

Let's look at how velocity is used in spring MVC by re-implementing the view layer in the spring training app based on velocity.

9.1.1 Defining the Velocity view

Suppose you have chosen to use velocity rather than JSP to create a view of the spring training app. One of the pages you need to write with the velocity template is the page that displays the list of available courses. Listing 9.1 shows the COURSELIST.VM, a velocity template that is equivalent to courselist.jsp for displaying a list of courses.

Program Listing 9.1 Velocity-based course list

<title>course list</title>

<body>

<table width= "border=" 1 "cellspacing=" 1 "cellpadding=" 1 ">

<tr bgcolor= "#999999" >

<td>course id</td>

<td>Name</td>

<td>Instructor</td>

<td>Start</td>

<td>End</td>

</tr>

#foreach ($course in $courses)

<tr>

<td>

<a href= "Displaycourse.htm?id=${course.id}" >

${course.id}

</a>

</td>

<td>${course.name}</td>

<td>${course.instructor.lastName}</td>

<td>${course.startDate}</td>

<td>${course.endDate}</td>

</tr>

#end//Cycle through all courses

</table>

</body>

Perhaps the first thing you notice is that there are no template tags in this template. This is because velocity is not based on a tag similar to a JSP, but rather uses its own language-called Velocity template Language (VTL)-for process control and other directives. In Courselist.vm, #foreach指令用于循环处理一个课程列表, displays the details of each course. In addition to the basic differences between the velocity and the JSP, you will find that velocity's expression language is similar to the JSP. In fact, when a JSP uses ${} as its own expression language, it is just a way of mimicking velocity. This template only demonstrates a very small amount of what you can do with velocity.

If you want to know more, you can access Velocity's home page in Http://jakarta.apache.org/velocity. Note When the template is finished, you need to configure spring so that it can use the velocity template as a view in the MVC app.

9.1.2 Configuring the Velocity engine

The first thing to configure is the velocity engine itself. To do this, you can declare a velocityconfigurer Bean in the spring configuration file in the following ways:

<bean id= "Velocityconfigurer" class= "Org.springframework.web.servlet.view.velocity.VelocityConfigurer" >

<property name= "Resourceloaderpath" >

<value>WEB-INF/velocity/</value>

</property>

</bean>

The velocityconfigurer is responsible for setting the velocity engine in spring. Here, we tell velocity where to look for its template through the attribute Resourceloaderpath. We recommend placing the template under one of the subdirectories of Web-inf, which guarantees that the templates cannot be accessed directly. You can also set the configuration details for other velocity by using the Velocityproperties property. For example, the following velocityconfigurer configuration:

<bean id= "Velocityconfigurer" class= "Org.springframework.web.servlet.view.velocity.VelocityConfigurer" >

<property name= "Resourceloaderpath" >

<value>WEB-INF/velocity/</value>

</property>

<property name= "Velocityproperties" >

<props>

<prop key= "Directive.foreach.counter.name" >loopCounter</prop>

<prop key= "Directive.foreach.counter.initial.value" >0</prop>

</props>

</property>

</bean>

You can notice that the Velocityproperties property uses a <props> element to set multiple properties. The properties you can set here are the same as those set by the "velocity.properties" file in a typical velocity application. By default, Velocity's #foreach loop maintains a loop counter called $velocitycount, which counts from 1 at the start of the first round of the cycle. But here we set the property directive.foreach.counter.name to Loopcounter, so we'll use $loopcounter to refer to the loop counter. We also make the loop counter count from zero by setting the property directive.foreach.counter.initial.value to 0. (For information on velocity configuration properties, please refer to the Velocity Developer Guide http://jakarta.apache.org/velocity/developer-guide.html.) )

9.1.3 Analytic Velocity View

The last thing you have to do to use the Velocity template view is to configure a view resolver. Specifically, you need to declare a velocityviewresolver Bean in the spring context configuration as follows:

<bean id= "Viewresolver" class= "org.springframework.

Web.servlet.view.velocity.VelocityViewResolver ">

<property name= "suffix" ><value>.vm</value></property>

</bean>

The relationship between Velocityviewresolver and velocity is similar to that of Internalresourceviewresolver and JSP. As Internalresourceviewresolver, it uses the prefix property and the suffix property to construct the path to the template file from the logical name of the view. Here we just set the suffix property to the ". VM" extension. Because the path to the template directory has been configured with the Resourceloaderpath property of Velocityconfigurer, there is no need to set a prefix here.

Note: This sets the Bean's ID to viewresolver. This is important because we have not configured Dispatcherservlet to detect all the view resolvers. If you want to use multiple view resolvers at the same time, you will most likely need to change the ID to a more appropriate name (and unique), such as Velocityviewresolver.

Your application is now ready to render a view based on the velocity template. You only need to refer to the desired view by logical name in the returned Modelandview object. Take Listcoursecontroller as an example, there is no need to do anything else because it has returned the following Modelandview object:

return new Modelandview ("Courselist", "courses", allcourses);

The logical name of the view is "Courselist". When this view is parsed, the "courselist" plus the suffix ". VM" constitutes a template name of "COURSELIST.VM". Velocityviewresolver will look for this template under the Web-inf/velocity path.

As for the "courses" model object, it is exposed as a velocity property to the velocity template for use. In Listing 9.1, it is the collection object that is used in the #foreach directive.

9.1.4 formatting dates and numbers

Although the app has been configured to render the velocity view, there are some assorted issues that need to be addressed. When you compare COUSELIST.VM and courselist.jsp in Listing 9.1, you will notice that COURSELIST.VM does not format the course ID, start date, and end date as courselist.jsp. In courselist.jsp, the course ID is displayed as a zero-padded number in front of a 6-bit fixed length, and all dates are displayed in full format. In order to complete the COURSELIST.VM, you need to make further adjustments to the ID and date attributes to be formatted.

The VTL does not directly support the formatting of dates and numbers, but rather supports formatting by providing a tool class of date and time. To allow the use of these tools, you need to tell Velocityviewresolver the name of the property used when exposing them in the template. These attribute names are specified by Velocityviewresolver's Datetoolattribute and Numbertoolattribute properties:

<bean id= "Viewresolver" class= "Org.springframework.web.servlet.view.velocity.VelocityViewResolver" >

...

<property name= "Datetoolattribute" >

<value>dateTool</value>

</property>

<property name= "Numbertoolattribute" >

<value>numberTool</value>

</property>

</bean>

Here, we specify that the digital tool is exposed to velocity using the Numbertool attribute. Therefore, to format the course ID, you only need to process the course ID by using the format () method of the digital tool, as follows:

$numberTool. Format ("000000", Course.id)

The first parameter of the method format () is a pattern string, where we specify that the course ID be displayed as a 6-digit field, and 0 if necessary. The syntax of the pattern string is consistent with the Java.text.DecimalFormat. Please refer to Velocity's documentation for Numbertool for more information on the functionality of this tool.

Similarly, we assign date tools to use the Datetool property. To format the start and end dates of a course, simply use the format () method of the date tool:

$dateTool. Format ("full", course.startdate)

$dateTool. Format ("full", course.enddate)

As with the format () method of the digital tool, the first parameter is also a pattern string. The syntax of a pattern string is consistent with Java.text.SimpleDateFormat. Alternatively, you can set the pattern string to one of full, LONG, MEDIUM, short, or default to use the standard Java.text.DateFormat mode. Here we set the pattern string to full to represent the complete date format. Please refer to Velocity's documentation on Datetool for more information on the tool's capabilities.

9.1.5 exposing requests and session properties

Although most of the data that needs to be displayed in the velocity template can be passed to the view through the model map of the Modelandview object, it is sometimes necessary to display the properties in the Servlet request or session. For example, when a user logs on to the application system, the user's information may be stored in a servlet session.

This can be awkward if you copy the properties of a request or session to a model map in each controller. Fortunately, Velocityviewresolver will help you copy these attributes into the model. The properties Exposerequestattributes and Exposesessionattributes tell Velocityviewresolver whether the servlet request and the properties in the session need to be copied into the model. Like what:

<bean id= "Viewresolver" class= "Org.springframework.web.servlet.view.velocity.VelocityViewResolver" >

...

<property name= "Exposerequestattributes" >

<value>true</value>

</property>

<property name= "Exposesessionattributes" >

<value>true</value>

</property>

</bean>

The default value for both properties is false. But here we set both properties to true so that the request and session properties are copied into the model and visible in the velocity template.

9.1.6 binding form fields in velocity

In the 8th chapter, we see how to bind a form field to a command object using spring's <spring:bind>jsp tag. This tag is also useful when displaying errors related to the form field to the user.

Fortunately, when you use velocity instead of a JSP, you don't have to give up the functionality that <spring:bind> provides. Spring provides a number of velocity macros to mimic the functionality of <spring:bind> tags.

For example, suppose the Student registration form for the spring training app was written with the velocity template. Listing 9.2 shows a section in REGISTERSTUDENT.VM that shows how to use the #springbind macro:

Listing 9.2 using #springbind in the velocity template

#springBind ("Command.phone")

Phone: <input type= "Text"

Name= "${status.expression}"

Value= "Http://www.blog.edu.cn/$!status.value" >

<font color= "#FF0000" >${status.errorMessage}</font><br>

#springBind ("Command.email")

Email: <input type= "Text"

Name= "${status.expression}"

Value= "Http://www.blog.edu.cn/$!status.value" >

<font color= "#FF0000" >${status.errorMessage}</font><br>

#springBind宏的参数是被绑定表单域的引用路径. It sets a variable named status in the template to hold the name of the form field, the value, and any error messages (possibly from an authenticator) that may appear.

If the error message contains characters that have special meaning in HTML (such as:<,>,&), you may need to escape the error message to display it correctly in the Web browser. In this case, you need to use macro #springbindescaped instead of #springbind:

#springBindEscaped ("Command.email", True)

In addition to the domain's reference path, the number of #springBindEscaped宏接受一个boolean参 indicates whether the HTML special characters in the error message need to be escaped. If this argument is false, the behavior of macro #springbindescaped and #springbind is exactly the same, and the HTML special characters are not escaped.

In order to use spring macros in a template, you need to use these macros through Velocityviewresolver's exposespringmacrohelpers:

<bean id= "Viewresolver" class= "Org.springframework.web.servlet.view.velocity.VelocityViewResolver" >

...

<property name= "Exposespringmacrohelpers" >

<value>true</value>

</property>

</bean>

By setting the Exposespringmacrohelpers property to True, you can use the #springbind and #springbindescaped macros in the velocity template.

Although Velocity is an alternative to a widely used JSP, it is not the only alternative template technology that can be used. Freemarker is another well-known template for replacing JSPs in the view layer of MVC applications

Use velocity templates in spring

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.