Interview Questions

Spring Velocity Integration

In this article lets discuss about how to integrate velocity framework with spring.

What is Velocity?

Velocity is an open sourced template based tool mostly used for formatting in the presentation layer (similar to jsp). You can create template files, access it in your application, fill the data dynamically in the templates and return it to view layer as you do for jsps.

Suppose if you want to send an email to a friend. You can create a template in velocity(shown below) representing the email format, and use the velocity api methods to fill in the template to get the final email message to be sent to the recipient.

email.vm

Dear $friendName
 
<p>
 $messageBody
</p>
 
Thanks & Regards,
$yourName

Lets see an example of how to display an html table in view using velocity framework in spring.

First create a velocity template representing html table as follows.

htmlTable.vm

<html>
<head>
<title></title></head>

<body>
<table border="1">
<tr>
        #foreach( $header in $headerLst )
    <th>
                <B>$header</B>
        </th>
        #end
</tr>
       
#foreach( $emp in $empList )
        <tr>
                <td>
                        $emp.empId
                </td>
                <td>
                        $emp.empName
                </td>
                <td>
                        $emp.age
                </td>
                <td>
                        $emp.salary
                </td>
                <td>
                        $emp.department
                </td>
        </tr>
#end    
</table>
</body>

</html>

Now create a Simple form controller in spring as follows

VelocityController.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class VelocityController extends SimpleFormController
{

        /*
         * (non-Javadoc)
         * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
         * javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException)
         */

        @Override
        protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
                        BindException errors) throws Exception
        {
               
                return super.onSubmit(request, response, command, errors);
        }

        /*
         * (non-Javadoc)
         * @see
         * org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest)
         */

        @Override
        protected Map referenceData(HttpServletRequest request) throws Exception
        {

                System.out.println("Inside referenceData - > ");
                Map context = new HashMap();
                List<Employee> lstEmp = new ArrayList<Employee>();
                List<String> headerLst = new ArrayList<String>();

                Employee emp1 = new Employee(1001, "George", 35, 50000, "IT");

                Employee emp2 = new Employee(1002, "Patrick", 41, 60000, "FINANCE");
                Employee emp3 = new Employee(1003, "Haggai", 32, 45000, "HR");
                Employee emp4 = new Employee(1004, "Jones", 29, 40000, "MARKETING");
                Employee emp5 = new Employee(1005, "Miller", 38, 54000, "SALES");

                lstEmp.add(emp1);
                lstEmp.add(emp2);
                lstEmp.add(emp3);
                lstEmp.add(emp4);
                lstEmp.add(emp5);

                headerLst.add("EMP_ID");
                headerLst.add("EMP_NAME");
                headerLst.add("AGE");
                headerLst.add("SALARY");
                headerLst.add("DEPARTMENT");

                context.put("headerLst", headerLst);
                context.put("empList", lstEmp);

                return context;
        }

        public VelocityController()
        {
                setCommandClass(Employee.class);
        }
}

We have just implemented referenceData method of the SimpleFormController. We have set a list of employee objects and set it in a Map.
Once the control returns from the Controller, the velocity template htmlTable.vm will be rendered and displayed in the UI.

Have a look at the spring application context file below.

velocity-servlet.xml

<bean id="urlMapping"
        class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <!-- URL and Corresponding Controller mapping to come here -->
        <property name="urlMap">
         <map>
           <entry key="/htmlTable.htm" value-ref = "velocityController"/>
         </map>
        </property>
</bean>
 
 
<bean id="velocityConfig"
        class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
        <property name="resourceLoaderPath">
            <value>/</value>
        </property>
</bean>  

<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
        <property name="prefix"><value>/WEB-INF/velocity/</value></property>
        <property name="suffix"><value>.vm</value></property>
</bean>
 
 
<bean id="velocityController" class="com.techdive.spring.VelocityController">
        <property name="formView" value="htmlTable" />
        <property name="successView" value="htmlTable" />
</bean>

</beans>

In the above file we have included necessary beans for velocity framework like VelocityConfigurer,VelocityViewResolver etc,. When the application is executed in an application server, an html table containing employee details will be displayed in UI.

In this way we can integrate velocity framework with spring in the view layer.

Note: velocity.jar file need to included in library path. The htmlTable.vm file should
be present in the WEB-INF/velocity/ folder inside the war file.