Tuesday, April 24, 2007

Velocity intergration with struts

            Velocity is a Java-based template engine. It permits anyone to use a simple yet powerful template language to reference objects defined in Java code.
            When Velocity is used for web development, Web designers can work in parallel with Java programmers to develop web sites according to the Model-View-Controller (MVC) model, meaning that web page designers can focus solely on creating a site that looks good, and programmers can focus solely on writing top-notch code.
        Velocity separates Java code from the web pages, making the web site more maintainable over its lifespan and providing a viable alternative to Java Server Pages (JSPs) or PHP.


Five steps to Velocity

The recipe for combining Struts and the Velocity Template Engine is simple and straightforward; in fact, you can do it in just five steps:

   1. Place the Velocity JARs in your classpath.
   2. Modify the web.xml file to recognize the Velocity servlet.
   3. Place the Velocity toolbox.xml under your application's WEB-INF directory.
   4. Modify your struts-config to point its views to Velocity templates instead of JSPs.
   5. Create a Velocity template for each page you want to render.

        Let us take up an example to understand better.When we search for an ISBN, it should display the contents of the isbn.. For this example let us execute the five steps..

Step 1. Place the Velocity JARs in WEB-INF/lib


The Step 1 is the easiest.Download velocity jars and place them in WEB-INF/lib

Step 2. Modify web.xml to recognize the Velocity servlet


The next step is to modify the Struts web.xml file to recognize the Velocity servlet and direct all resources

request ending with .vm to the Velocity servlet

<servlet>
  <servlet-name>velocity</servlet-name> //declare the Velocity servlet and give it a handle of velocity.
  <servlet-class>
    org.apache.velocity.tools.view.servlet.VelocityViewServlet
  </servlet-class>                                            

  <init-param>
    <param-name>org.apache.velocity.toolbox</param-name>// toolbox configuration location.
    <param-value>/WEB-INF/toolbox.xml</param-value>      
 </init-param>                                                 

 <load-on-startup>10</load-on-startup>
</servlet>

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


The Velocity servlet takes a "toolbox" parameter. The toolbox is the place you declare the tools available to

your application.

Step 3. Place toolbox.xml under WEB-INF

The tool box bascially conntains all the tools. We define each of them with the key,scope and the class..

<?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>

Step 4. Modify struts-config

    Struts config should be modified to support velocity. There is no much difference if we have a velocity template forward the action to a *.vm pattern

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD
             Struts Configuration 1.0//EN"
          "http://jakarta.apache.org/struts/dtds/
            struts-config_1_0.dtd">

<struts-config>
    <form-beans>
        <form-bean name="searchForm" type="app.SearchForm"/>
    </form-beans>

    <global-forwards>
        <forward name="welcome" path="/welcome.do"/>
    </global-forwards>
 
   <action-mappings>
        <action
            path="/welcome"
            type="org.apache.struts.actions.ForwardAction"
            parameter="/pages/search.vm"/>

        <action
            path="/search"
            type="app.SearchAction"
            name="searchForm"    
            scope="request"
            input="/pages/search.vm">
            <forward name="success"
              path="/pages/results.vm"/>
        </action>
    </action-mappings>
</struts-config>
Note that we can use both *.do and *.vm in the same application depending on the requirement.

Step 5. Create a Velocity template


velocity template for the example application's search page.

HTML>
  <HEAD>
    <TITLE>Search</TITLE>
  </HEAD>
  <BODY>
    $!errors.msgs() //$!errors.msgs() to get any error messages on the error-message queue.
    <FORM method="POST"
      action="$link.setAction('/search')"> //to obtain the URL for the search forward.
      <h2>Book Search</h2>
      ISBN:<INPUT type="text" name="isbn">
      <INPUT type="submit" value="Submit" name="submit">
    </FORM>
  </BODY>
</HTML>
     
Velocity template for the results page

<html>
  <body>

  <h1>Book Details</h1>
  <a href="$link.setForward("searchEntry")">Search
    again</a>

  <h3>$book.title</h3>

    <b>ISBN:</b>$book.isbn<br>
    <b>Title:</b>$book.title<br>
    <b>Author:</b>$book.author<br>
    <b>Price:</b>$book.price<br>
    <b>No Pages:</b>$book.pages<br>
    <b>Description:</b>$book.description<br>
    <b>Publisher:</b>$book.publisher<br>
  </body>
<html>

The action class sets a book object in session, which is retrieved and displayed in the velocity template.

This is a sample application with velocity and struts. Velocity does seems simpler than JSP's

1 comment:

Jenni Aloi, IBM developerworks said...

This "post" has been lifted from IBM developerWorks and is in violation of copyright law. The original content is by George Franciscus and is available here: http://www.ibm.com/developerworks/java/library/j-sr1.html

"Innovations at Work," my arse. There's nothing more slimy that passing off someone else's work as your own. Tsk Tsk.