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
<servlet>Now create a hello-world.vm file in the root directory of your web resources, where you would normally put JSP files.
<servlet-name>velocity</servlet-name>
<servlet-class>
org.apache.velocity.tools.view.servlet.VelocityViewServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>velocity</servlet-name>
<url-pattern>*.vm</url-pattern>
</servlet-mapping>
<html>
<body>
Hello World at $currentTime!
</body>
</html>
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"/>
</action>
In HelloWorldAction class:
request.setAttribute("currentTime", new Date());
return actionMapping.findForward("ok");
Start application and access http://localhost:8080/struts-velocity/hello-world.do 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.