9.13. Using Velocity in a Web Application

Problem

You are sick of writing JSP and having to wait for pages to compile. You would like to find a way to use Velocity instead of JSP.

Solution

Configure your web application to use the VelocityViewServlet to render your Velocity templates. Download the latest version of the VelocityView project from http://jakarta.apache.org/site/binindex.cgi; it is listed under “Velocity Tools 1.1.” Put the velocity and velocity-tools jars in the WEB-INF/lib directory, and configure your web application to render templates ending in *.vm with the VelocityViewServlet. Add the following servlet and servlet-mapping elements to your web.xml file as follows:

<!-- Define Velocity template compiler -->
<servlet>
  <servlet-name>velocity</servlet-name>
  <servlet-class>
    org.apache.velocity.tools.view.servlet.VelocityViewServlet
  </servlet-class>
  <load-on-startup>10</load-on-startup>
</servlet>

.....other servlets.....

<!-- Map *.vm files to Velocity -->
<servlet-mapping>
  <servlet-name>velocity</servlet-name>
  <url-pattern>*.vm</url-pattern>
</servlet-mapping>

All requests ending in *.vm are processed by the VelocityViewServlet, which locates the appropriate Velocity template in the document root of your web application. Attributes from the request, session, and application scope will be available as variables in the VelocityContext.

To test this configuration, create a simple Velocity template in the document root of your web application named index.vm, start your servlet ...

Get Jakarta Commons 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.