• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

Spring with Apache Velocity

March 9, 2011 //  by Krishna Srinivasan//  Leave a Comment

Introduction

Spring is an open source framework, created by Rod Johnson. We can develop many kinds of applications using Springwhich includes basic java programs and enterprise applications. Any Java application can benefit from Spring in terms of simplicity, testability, and loose coupling. Spring supports integration with Struts, WebWork, Apache velocity , Hibernate, JDO, TopLink, EJB, RMI, JNDI, JMS, Web Services, etc. This article assumes that readers has the sufficient knowledge on Spring Framework. If you are beginner looking for basic concepts on Spring Framework, please read Introduction to Spring Framework.

also read:

  • Spring Tutorials
  • Spring 4 Tutorials
  • Spring Interview Questions

Apache Velocity is a Java Template Engine which is one of the Jakarta projects . Templates are processed and but they are not compiled. It is ASF-licensed s/w. Velocity is a good alternate to Java Server Pages (JSPs) and is used to generate web pages, Java source code and other output from templates. It is useful for generating source code and reports. We can integrate Velocity as a view with Struts 2.0 , Spring frameworks etc. It supports better separation of code and design ,no compilation into Java code and also there is no embedded Java code. For details please visit http://velocity.apache.org/.

Spring’s Web MVC Framework

Spring Web MVC framework is to develop Spring Web applications and also it allows integration with other Web MVC frameworks and different View technologies like Velocity , Freemarker,etc. Spring MVC is based on DispatcherServlet that receives requests and delegates to the appropriate controllers. For details please visit http://www.springsource.com.

Apache Velocity

Apache Velocity Velocity is 100% Pure Java based template language .We can run Velocity on Java 1.3 or above versions. Apache Velocity current release is 1.7.
When compares with JSP, Velocity is easy to test, also no need of a Servlet container.It supports better separation of code and design ,no compilation into Java code and also there is no embedded Java code.

Velocity Language Elements are:
Statements,Directives,References,Comments

Sample code :

<html><body>
##This is a Velocity Application

<br>
#set( $message = " Hello World " )
$message 

</body>
</html>

The above example will give the output HelloWorld

In the above example :

##This is a Velocity Application is a comment.

#set( $message = ” Hello World ” ) is a statement

set is a directive

$message is a reference

Spring integration with Velocity

Spring supports the separation of view technologies from the rest of the MVC framework. For example we can use Velocity or XSLT in the place of JSPs. For this kind of integration with other views we need to configure for ViewResolver in Spring-servlet.xml file.
The view resolver for JSP is InternalResourceViewResolver. Incase of velocity we have to configure with org.springframework.web.servlet.view.velocity.VelocityViewResolver.

The software tools required for this example are as below:

  • NetBeansEditor 6.9.1,JDK1.6
  • Spring MVC jars
  • velocity-tools-view-1.4.jar ,velocity-dep-1.5.jar, velocity-tools-view-1.4.jar

The below example demonstrates how to use the velocity as the output view in a Spring Application. This is developed as a Netbeans Webapplication Project and it contains the files Input.jsp ,Result.vm, SumController.java,dispatcher-servlet.xml,web.xml.When we executes this spring application the Input.jsp will load .

This application is a Sum webapplication ,which can calculate the sum of two integer numbers and the output is dipalying using a velocity.The configurations of Spring MVC and Velocity integration is present in the dispatcher-servlet.xml.The sumcontroller class is the actual controller class,which contains the the model and view.In this example , the model logic is for finding the sum of two numbers and the view page is Result.vm.Also we need to add all the necessary libraries for this application.The details about the libraries are already present in the article .

Input.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
    <head>

    </head>

    <body bgcolor="yellow">
        <h1><b> Sum Application</b></h1>
        <hr>
            <br>

        Please Enter the Input 
        <br>

        <form action="sum.htm">
            <table>
      <b>  <tr><td>First  no: </td><td> <input type="text" name="no1"/></td></tr></b>
       <br><br>
      <b><tr> <td>Second no: </td><td><input type="text" name="no2"/></td></tr></b>
            <br></table>
          <input type="submit" value="SUM"/>
        </form>
    </body>
</html>

Result.vm

<html>
    <head>
        <title>Output Page</title>
    </head>
  <body bgcolor="pink">
 <h1><B>  <center> The OutPut is: </center></B></h1>

             <big>  <center>     ${sum}</center></big>
    </body>
</html>
[/jaa]

<strong>dispatcher-servlet.xml</strong>


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<bean id="urlMapping">

<property name="mappings">
            <props>

                sumController</prop>
            </props>
        </property>
    </bean>

    <bean id="sumController" />
<bean id="velocityConfig"
       >

        <property name="resourceLoaderPath" value="/"/>

</bean>

    <bean id="viewResolver"

          p:prefix="/WEB-INF/rasmi-jsp/"
          p:suffix=".vm" />

</beans>

SumController.vm

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class SumController extends AbstractController {

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest requs, HttpServletResponse repns) throws Exception {
        int n1=Integer.parseInt(requs.getParameter("no1"));
         int n2=Integer.parseInt(requs.getParameter("no2"));
         int s1=0;
         s1=n1+n2;

        return new ModelAndView("Result", "sum", s1);
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>Input.jsp</welcome-file>
        </welcome-file-list>
    </web-app>

Exceute the application in any browser

Output

Conclusion

This article gives the basic idea about Spring framework and Apache Velocity .It contains an example which is a Spring Webapplication,which is for finding the sum of two integer numbers .All the necessary files and other informations for developing this example is specified in the article.The main idea of this example is how to do the integration of Apache Velocity and Spring.The dispatcher-servlet.xml contains all the necessary configurations for ViewResolver and VelocityConfigurer. I think this article will help you for developing similar kinds of examples in spring.

also read:

  • Spring Books
  • Introduction to Spring Framework
  • Introduction to Spring MVC Framework

If you have any questions on the spring framework  please post it in the comments section. Also search in our website to find lot of other interesting articles related to the spring framework. There are some interesting articles about spring framework, interview questions, spring and hibernate integration,etc.
If you would like to receive the future java articles from our website, please subscribe here.

Category: Spring FrameworkTag: Apache Velocity, Spring MVC

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Previous Post: « Introduction to Spring REST Services
Next Post: Jasper Reports and Data Sources »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact