Wednesday, December 5, 2007

How to use Velocity as a view component in Struts?

Struts provides a proved framework for building web applications in Java. It is most often used with JSP as a view component. However, other view components may be used as well.

Here I will show how to create a "hello world" application using Struts and Velocity as a view component. I assume you have already downloaded and set up necessary Struts parts.

First of all, we need to download VelocityTools package which provides easy way to use "*.vm" (Velocity Macro) templates to serve HTML pages and has some tools for Struts integration.

Extract the archive and copy following jar files to your project:
  • velocity-tools-1.4.jar
  • velocity-1.5.jar
  • commons-beanutils-1.7.0.jar
  • commons-logging-1.1.jar
  • commons-collections-3.2.jar
  • oro-2.0.8.jar
  • commons-digester-1.8.jar
  • commons-lang-2.2.jar

Add following servlet definition and mapping to your web.xml:

Now create a hello-world.vm file in the root directory of your web resources, where you would normally put JSP files.
Hello World at $currentTime!

If you start application and point your browser to the http://localhost:8080/struts-velocity/hello-world.vm URL, you will see following output:
  Hello World at $currentTime!    

Create HelloWorldAction Struts Action to add necessary "currentTime" object to the request.

In struts-config.xml:
  <action path="/hello-world" type="vilbara.HelloWorldAction">
<forward name="ok" path="/hello-world.vm"/>

In HelloWorldAction class:
  request.setAttribute("currentTime", new Date());
return actionMapping.findForward("ok");

Start application and access http://localhost:8080/struts-velocity/ URL. You will get following output:
  Hello World at Thu Dec 06 12:36:33 CET 2007!

That was it. Now Struts uses Velocity for the view component in your application.

You may download struts-velocity.war file. Sources are included.

No comments: