Helping ordinary people create extraordinary websites!
GET OUR NEWSLETTER
Your Email:
 

Client and server-side templating with Velocity

By Sing Li
2004-06-13


Interoperating with the Struts framework

Struts is a popular Web application building framework based on the MVC model. The default view component technology for Struts is JSP technology. However, you can easily integrate Velocity as the view component. Figure 1 illustrates this specific use of Velocity:

Figure 1. Integrating Velocity with the Struts MVC framework


It is important to note that Velocity does not displace JSP technology in this composition. Instead, JSP technology and Velocity templates can work alongside one another. To integrate Velocity, configure VelocityViewServlet to process .vm templates, as we described in the Deploying VelocityViewServlet section. This means that .jsp files will continue to be processed by the container (that is, Jasper in Tomcat 5), while any .vm templates are passed to Velocity.

The VelocityStruts component of the Velocity Tools subproject (see Resources) has everything you need to integrate Velocity with Struts. VelocityStruts provides a set of specialized Velocity tools to access Struts-specific resources and information within a Velocity template. Table 3 provides a brief list of the most frequently used tools:

Table 3. Tools for VelocityStruts integration

Tool Name: Description
StrutsLinkTool: Specialized version of the LinkTool for working with Struts targets. Provides setAction() and setForward() to access the pre-configured action mappings.
FormTool: Accesses Struts's form beans.
ErrorsTool: Works with Struts error messages, including support for internationalization.
MessageTool: Provides access to Struts's internationalization support, more specifically the language-dependent message resources.

There is also a set of tools available specifically for working with the new features in Struts 1.1, as shown in Table 4:

Table 4. Specialized Struts 1.1 access tools

Tool Name: Description
SecureLinkTool: Works with Struts 1.1's secured link (SSL) extension.
ActionMessagesTool: Provides access to Struts 1.1's new ActionMessages object.
TilesTool: Provides access to Struts 1.1's Tiles extension support.
ValidatorTool: Provides access to Struts 1.1's Validator extension, generating code to validate form input fields.

In the webapps\struts-example directory, you will see an example of using Struts instead of JSP technology to create Struts pages. In this case, we replace the first title page of the example Web application distributed with Struts. You may want to try your hand at replacing other pages. The following list describes the steps involved.

1. Copy the Velocity libraries into the WEB-INF\lib directory of the struts-example application. Using Tomcat 5 (5.0.16 is latest at the time of writing) and Struts 1.1, you will need to copy the following JAR files into the webapps\struts-example\WEB-INF\lib directory:
•velocity-tools-1.1-beta1.jar
•velocity-1.4-rc1.jar

2 Next, in the Struts configuration file (WEB-INF\struts-config.xml), the Struts action mapping is set to forward to the index.vm file instead of the index.jsp file, as shown in Listing 22:

Listing 22. Modifying Struts action forward to \ index.vm

<action path="/logoff"
   type="org.apache.struts.webapp.example.LogoffAction">
<forward name="success" path="/index.vm"/>
</action>

3. In the deployment descriptor WEB-INF\web.xml file, configure VelocityViewServlet to process .vm files. Also set the welcome file to index.vm instead of index.jsp, as shown in Listing 23:

Listing 23. Modifying the deployment descriptor of the struts-example Web application
<!-- Action Servlet Configuration -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml,
/WEB-INF/struts-config-registration.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>


<servlet>
<servlet-name>velocity</servlet-name>
<servlet-class>org.apache.velocity.tools.view.servlet.VelocityViewServlet
</servlet-class>
<init-param>
<param-name>org.apache.velocity.toolbox</param-name>
<param-value>/WEB-INF/toolbox.xml</param-value>
</init-param>
<init-param>
<param-name>org.apache.velocity.properties</param-name>
<param-value>/WEB-INF/velocity.properties</param-value>
</init-param>
</servlet>


<!-- Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>velocity</servlet-name>
<url-pattern>*.vm</url-pattern>
</servlet-mapping>


<!-- The Welcome File List -->
<welcome-file-list>
<welcome-file>index.vm</welcome-file>
</welcome-file-list>


4. Last but not least, copy the toolbox.xml and velocity.properties files from this article's source code download (see Resources) to the WEB-INF directory.

The new index.vm file is shown in Listing 24. You may want to compare this with the original index.jsp file.

Listing 24. Struts interoperation through use of the index.vm Velocity template

<html>
<head>
<title>$msg.get("index.title")</title>
</head>
<body bgcolor="white">

#if ( !$application.database)
<font color="red">
ERROR: User database not loaded -- check servlet container logs
for error messages.
</font>
<hr>
#end

<h3>$msg.get("index.heading")</h3>
<ul>
<li>
<a href="$link.setURI("editRegistration.do").addQueryData("action","Create")">
$msg.get("index.registration")
</a>
</li>
<li>
<a href="$link.setURI("logon.jsp")">
$msg.get("index.logon")
</a>
</li>
</ul>

<p> </p>
<a href="$link.setURI("tour.do")">
<font size="-1">$msg.get("index.tour")</font>
</a>
<p> </p>
<img src="$link.setURI("powered-by-logo.gif")" alt="Powered by Velocity"/>
</body>
</html>


In index.vm, the message tool in $msg is used throughout this template to access Struts's locale-dependent, internationalized resources. This approach eliminates most hard-coded strings in the template, localizing changes to the resource bundle containing the internationalized strings.

You can use the conditional #if directive of VTL to directly check for the existence of the database attribute in the servlet context. The $application reference can be used to access any attribute in the servlet context ($request, $response, and $session are also available to access attributes of other Servlet API objects).

The setURI() method of the LinkTool is used to generate a server-side URI link to Struts's actions, as well as to the "Powered by Velocity" logo image. Note the use of the addQueryData() method of the LinkTool to append additional action information to a resulting URI.

You can test the Velocity page by starting Tomcat 5 and accessing the http://localhost:8080/struts-example/ URL. Note how it works identically to the original JSP version.

Tutorial Pages:
» Client and server-side templating with Velocity
» Basic template engine operation
» Velocity contexts
» Velocity as a standalone parser
» Velocity vs. JSP technology on the server
» Deploying Velocity with Tomcat 5
» Interoperating with the Struts framework
» Conclusions
» Resources


First published by IBM developerWorks


 | Bookmark
Related Tutorials:
» All about JAXP, Part 1
» Make Database Queries Without the Database
» Load List Values for Improved Efficiency
» 2 Ways To Implement Session Tracking
» A Simple Way to Read an XML File in Java
» Develop Aspect-Oriented Java Applications with Eclipse and AJDT

Advertise with Us!


Tutorials Scripts Web Hosting Developer Manuals
Resources