The Velocity Project < Velocity Tools - Struts >

Velocity Tools

VelocityStruts

VelocityStruts Tools

Other Subprojects

VelocityStruts User Guide

This guide explains how to setup and configure a VelocityViewServlet which can render the views of a Struts-based web application. The servlet will create a VelocityEngine to render *.vm (velocity template) files using contextual information provided by a Struts Controller action.

A set of built-in tools have been created which provide the same functions as the Struts JSP Tag libraries for Tiles, Validator, forms, links, messages, and errors.

The distribution contains examples which demonstrate the use of the built-in Struts tools. The examples are packaged into a web archive file (velstruts.war).

This document is not a general introduction to the Velocity template language and its syntax. If you are new to Velocity, please consult Getting Started with Velocity.

Table of Contents

  1. Background
  2. Model 2 Architecture
  3. Installation
  4. Rendering the View
    1. Velocity Template Language
    2. Exposing Data
    3. Access to Servlet Resources
    4. Access to Struts Framework Resources


Background

The documentation will explain the steps necessary to integrate Velocity with Struts 1.x applications. It is expected that the reader already has a basic understanding of those projects.

To start working with Velocity and Struts we recommend reading the user guide, installing and browsing the example applications and reference documentation, then installing the VelocityStruts view layer into your own application.

If this documentation does not answer all your questions, please post questions to the Velocity-User mailing list and we'll be happy to help! (And we'll update this doc!)



Model 2 Architecture

In the JSP world, the terms Model 1 architectures and Model 2 architectures were coined to refer to particular ways of designing and building web applications. It is important that you understand the fundamental difference between these two architectural approaches. JSP can be used in applications designed after Model 1 architectures as well as Model 2 architectures. Velocity cannot. It has been designed very consciouly as a view technology for web application architectures based on Model 2.

Model 1 Architectures

In a Model 1 architecture, the JSP page alone is responsible for processing the incoming request and replying back to the client. Using MVC speak, the controller and the view are implemented within the same JSP page. Model 1 architecture are suitable only for very simple application scenarios. In medium size to large projects, the lack of a separation between business logic and view oftentimes leads to difficulties in separating the web designer's works from the server developer's work and causes project management headaches.

Model 2 Architectures

In a Model 2 architecture, the control component, including business logic, data access and request handling, are strictly separated from the view component. The view does not contain any processing logic. It is simply responsible for displaying the data that resulted from processing the request. This may be a static page or more often a dynamic page. Such an approach typically facilitates are clear delineation of the roles and responsibilities of the developers and the web designers. The more complex an application, the greater the benefits of using a Model 2 architecture will be.

The paper Understanding JavaServer Pages Model 2 Architecture provides a more in-depth discussion of Model 1 and Model 2 architectures.

What does this mean?

The Struts framework can support both architectures, but all the facilities it provides are really aimed at making the construction of Model 2 applications easy. Velocity on the other hand cannot be used to build Model 1 architectures. It lacks the libraries to support such a design. I am emphasizing this here because I want to make sure that you have all the relevant facts before you decide on Velocity for your projects. This is especially important for people considering to port existing application built on the Model 1 approach or a mixed Model 1 / Model 2 approach. The good news is, that today for any serious application Model 2 is state of the art and Velocity will support you very well on that route.



Installation

This section explains the basic setup to configure the VelocityViewServlet to render the web application views in Struts applications.

Setup is almost identical to the standard VelocityViewServlet installation, please review that for more details. The extended VelocityLayoutServlet, or any custom extension, can also be used with Struts. (That particular servlet adds the ability to reuse shared html layout across multiple pages.)

Steps by step:

  1. velocity-tools-x.x.jar which contains the VelocityStruts and VelocityView classes must be added to the WEB-INF/lib directory.
  2. VelocityViewServlet needs to be installed into the servlet container (web.xml) so it can handle all request for *.vm files.
  3. velocity.properties configuration file must be added
  4. toolbox.xml file must be added, and mappings must be setup for the standard tools which expose the Struts objects to the template. (sample toolbox.xml file below)

And that's all there is to it!

At this point, it should be possible to change a Struts ActionMapping to 'forward' to a *.vm file placed in the webapp root directory and have it be displayed!

toolbox.xml


<?xml version="1.0"?>

<toolbox>
  <tool>
     <key>link</key>
     <scope>request</scope>
     <class>org.apache.velocity.tools.struts.StrutsLinkTool</class>
  </tool>
  <tool>
     <key>msg</key>
     <scope>request</scope>
     <class>org.apache.velocity.tools.struts.MessageTool</class>
  </tool>
  <tool>
     <key>errors</key>
     <scope>request</scope>
     <class>org.apache.velocity.tools.struts.ErrorsTool</class>
  </tool>
  <tool>
     <key>form</key>
     <scope>request</scope>
     <class>org.apache.velocity.tools.struts.FormTool</class>
  </tool>
  <tool>
     <key>tiles</key>
     <scope>request</scope>
     <class>org.apache.velocity.tools.struts.TilesTool</class>
  </tool>
  <tool>
     <key>validator</key>
     <scope>request</scope>
     <class>org.apache.velocity.tools.struts.ValidatorTool</class>
  </tool>
</toolbox>


Rendering the View

This section introduces you to the key concepts of rendering the view with Velocity in a Struts application.


Velocity Template Language

Velocity is a template engine implemented in Java. Velocity templates typically are HTML pages with embedded scripts (although Velocity has been used for many other application scenarios). Scripts are written in the Velocity Template Language (VTL). Following is a simple example of a HTML view with embedded VTL statements:


<HTML>
<BODY>
    <h2>Order Confirmation</h2>

    <h3>Delivery Adress:</h3><br>
    Name: $customer.name<br>
    Street: $customer.street<br>
    City: $customer.zip $customer.city

    <h3>Ordered Items</h3><br>
    <table>
    #foreach( $item in $order.items )
        <tr>
            <td>$item.quantity</td>
            <td>$item.description</td>
        </tr>
    #end
    </table>
</body>
</html>

When processed this will produce output similar to the following.


<HTML>
<BODY>
    <h2>Order Confirmation</h2>

    <h3>Delivery Address:</h3><br>
    Name: Peter Pan<br>
    Street: Crain St. 10<br>
    City: 60201 Evanston IL

    <h3>Ordered Items</h3><br>
    <table>
        <tr>
            <td>1</td>
            <td>Hair Dryer, Philips, 1000W, white</td>
        </tr>
        <tr>
            <td>1</td>
            <td>Kitchen Mixer, Betty Bossy, 240W, black</td>
        </tr>
    </table>
</body>
</html>

VTL has been designed from the ground up as a simple template language for view designers. With less than ten supported directives it is easy to learn. In fact, most people are up and productive within less than a day.

Velocity does not allow Java scriptlets, which helps enforce a strict MVC separation.

Please consult the following two documents for an in-depth coverage of VTL:




Exposing Data

The main purpose of Velocity in a web application is typically to merge HTML templates with dynamic application data to generate dynamic views. An essential aspect of Velocity is therefore the mechanism that allows the application controller (in MVC speak) to expose data to the template.

It is important to understand the relationship between a Struts-based application and the Velocity template servlet. Both are simply Java Servlets which perform a specific task.

Requests to the Struts application are processed, application data is manipulated and eventually all data and control is forwarded to a View layer.

The Velocity servlet in this case is responsible for merging the provided application data with a template to produce HTML output.

We should note that the Velocity servlet is not exclusively tied to the Struts application. It can serve requests from web clients directly or any other servlet application as well. Technically, the Struts application hands over a request to Velocity through the forward method of javax.servlet.RequestDispatcher.

Application data is passed from the Struts servlet to the Velocity servlet as attributes of either the servlet request, session or context.

Therefore a developer simply needs to set an attribute to pass data to the View layer and make that data available for the template. For example:

request.setAttribute("Customer", CustomerObj); Whatever public methods are available on the CustomerObj instance will be made available to the template designer. Assuming there is a public getName() method, they may for example write: $Customer.name or $Customer.getName().

There is a heirarchy to the objects exposed to the template designer. For instance, if you have set an attribute "foo" in both the session and the request,

request.setAttribute("foo", "request foo");
session.setAttribute("foo", "session foo");

then the request attribute will take priority, and using

$foo

in the template will give you

request foo

Priority is given in the following order:

  1. Tools specified in the toolbox.xml (e.g. $link, $tiles, etc.)
  2. The servlet classes (e.g. $request, $response, $session, $application)
  3. References set locally within the template
  4. Request attributes
  5. Session attributes
  6. Servlet context (application) attributes

This heirarchy allows the developer to reserve control of key references (for tools and servlet resources) from the template designer and allows for values to be set at various servlet scopes in a manner similar to working with JSP and Struts.




Access to Servlet Resources

VelocityStruts automatically populates the context with the following objects of the Servlet API on each template processing request:

Context Key Class Remarks
$request javax.servlet.http.HttpServletRequest the current servlet request
$session javax.servlet.http.HttpSession the current session, if one exists
$application javax.servlet.ServletContext the servlet context
$response javax.servlet.http.HttpServletResponse the current servlet response

The following examples illustrates how servlet resources are accessed from within Velocity template. The example renders the list of HTTP header fields of the current servlet request. In the same way, any public method of the above listed objects can be called from within templates:

#foreach( $header in $request.HeaderNames )
  <b>$header:</b> $request.getHeader($header)<br>
#end

The resulting output is something like this:

Referer: http://localhost:8080/struts/doc/examples.html
Connection: Keep-Alive
User-Agent: Mozilla/4.79 [en] (Windows NT 5.0; U)
Pragma: no-cache
Host: localhost:8080
Accept: image/gif, image/jpeg, image/pjpeg, image/png, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: JSESSIONID=aaaecXd7bnLPAr



Access to Struts Framework Resources

The Struts framework provides resources that are useful to template designers. These include logical names for physical resources, internationalized messages, error handling, form handling, etc. The interesting question is now how template designers can gain access these framework resources. In the JSP world, a set of custom tag libraries provide template designers access to the Struts framework resources. In the Velocity world, the equivalent of the JSP custom tag libraries are view tools. View tools are a very simple concept. They are Java objects with public methods that are put into the Velocity context. Tools are accessed by key and allows template designers to call on their public methods.

A set of seven view tools is included with VelocityStruts that provide template designers access to Struts framework resources. These seven view tools essentially achieve the integration between Struts and Velocity and they can be considered the core of this project.

Context Key Class Remarks
$text MessageTool Provides access to the Struts application resources for internationalized text.
$errors ErrorsTool Provides methods to check for and output Struts error messages.
$messages ActionMessagesTool Provides methods to work with Struts action messages.
$link StrutsLinkTool Provides methods to work with URIs.
$form FormTool Provides miscellaneous methods to work with forms and form beans in the context of Struts applications.
$tiles TilesTool Provides miscellaneous methods to work with Tiles in the context of Struts applications.
$validator ValidatorTool Provides methods to dynamically generate javascript validation in the context of Struts applications.
Note: The shown keys are the recommended values. They can be changed in the configuration.

The following example illustrates some of the features of the MessageTool for working with internationalized messages. For the example we assume that the Struts message resources contain the following two key=value pairs:


title=Struts Example Application
test=This string has 4 replacement parameters: {1}, {2}, {3}, {4}
foo.bar=whatever

Then, the following script...


$text.title
$text.get('test', ['bear', 'dog', 'cat'])
$text.exists('tutle')
$text.foo.bar

..will produce this output:


Struts Example Application
This string has 4 replacement parameters: bear, dog, cat, {4}
false
whatever

Please see the Tool Reference Documentation for more details about the view tools. Furthermore, the Velocity/Struts example application comes with several working examples that show how these tools are used.






Copyright © 1999-2003, Apache Software Foundation