14.9. Integrating Struts and Velocity

Problem

You want to use a template engine for HTML page generation instead of JSPs in your Struts application.

Solution

Integrate the Velocity template engine into your Struts application, replacing your JSP pages with Velocity templates.

Discussion

The Velocity template engine (http://jakarta.apache.org/velocity) can create any kind of textual document by merging Java objects with a template. The template document contains special markup that Velocity parses and replaces with values from Java objects stored in a template context.

When you use Velocity with Struts, instead of forwarding to JSP pages, you forward to a Velocity template. The Velocity servlet services the request, processing the template through the Velocity template engine and returning the generated HTML as the response.

Here's an action, adapted from the Struts MailReader example, that forwards to a Velocity template to display the "Welcome" page:

<action    path="/WelcomeVel"
           type="org.apache.struts.webapp.example.WelcomeAction">
    <forward name="failure" path="/Error.jsp" />
    <forward name="success" path="/welcome.vm" />
</action>

To use Velocity with Struts, you'll need to download the Velocity distribution from http://jakarta.apache.org/velocity. You also need to download the VelocityTools from http://jakarta.apache.org/velocity/tools/. VelocityTools includes helper classes that allow you to reference Struts-managed objects such as the action form and message resources. From the Velocity ...

Get Jakarta Struts Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.