You are on page 1of 91

Spring

Ravikumar Maddi
MessageSource
 Spring currently provides two MessageSource
implementations. These are the
ResourceBundleMessageSource and the
StaticMessageSource.
Example
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>applicationprop</value>
</list>
</property>
<bean>
<!-- let's inject the above MessageSource into this POJO -->
<bean id="example" class="com.techfaq.Example">
<property name="messages" ref="messageSource"/>
</bean>
---------------------------------------------------------------------------------------------------------------------
public class Example {
private MessageSource messages;
public void setMessages(MessageSource messages) {
this.messages = messages;
}
public void execute() {
String message = this.messages.getMessage("user.required",
new Object [] {"UserName"}, "Required", null);
System.out.println(message);
message = this.messages.getMessage("passwd.required",null, "Required", null);
System.out.println(message);
}
}
applicationprop.properties file in classpath.
# in 'applicationprop.properties'
passwd.required=Password Required!
user.required= '{0}' is required.

out put is :
Password Required!
UserName is required.
Constructor Ingection
<?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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
                http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/util
                http://www.springframework.org/schema/util/spring-util.xsd">
    <bean id="encyclopedia"
          name="mybean"
          class="Configure">
        <constructor-arg>
            <util:map>
                <entry key="CompanyName" value="Roseindia.net"/>
                <entry key="Address" value="Rohini"/>
            </util:map>
        </constructor-arg>
    </bean>
    <bean id="company" class="Companyinformation">
        <property name="encyclopedia" ref="mybean"/>
    </bean>
</beans>
public class Main {
public class Main {
    public static void 
    public static void main(String[] a) {
main(String[] a) {
        XmlBeanFactory beanFactory = new 
        XmlBeanFactory beanFactory = new XmlBeanFactory(
XmlBeanFactory(new 
new ClassPathResource("context.xml"));
ClassPathResource("context.xml"));
        company mycomp = (company) beanFactory.getBean("company");
        System.out.println("Name of the company is: " + mycomp.Name());
        System.out.println("Address of the company is: " + mycomp.address());
    }
}
interface company {
interface company {
    String Name();
   String address();
}
interface Detail {
interface Detail {
    String find(String entry);
}
class Companyinformation 
class Companyinformation implements 
implements company {
company {
    private 
    private Detail detail;
Detail detail;
    public 
    public String Name() {
String Name() {
        String name = this
        String name = this.detail.find("CompanyName");
.detail.find("CompanyName");
        return 
        return String.valueOf(name);
String.valueOf(name);
    }
    public 
    public String address() {
String address() {
        String add = this
        String add = this.detail.find("Address");
.detail.find("Address");
        return 
        return String.valueOf(add);
String.valueOf(add);
    }
    public void 
    public void setEncyclopedia(Detail d) {       
setEncyclopedia(Detail d) {       this
this.detail = d;    }
.detail = d;    }
}
class Configure 
class Configure implements 
implements Detail {
Detail {
    private 
    private Map map;
Map map;
    public 
    public Configure(Map map) {
Configure(Map map) {
        Assert.notNull(map, "Arguments cannot be null.");
        this
        this.map = map;
.map = map;
    }
    public 
    public String find(String s) {
String find(String s) {
        return 
        return (String) 
(String) this
this.map.get(s);
.map.get(s);
    }
}
Spring MVC
In web.xml file
<web-app>
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

</web-app>
 With the above servlet configuration , you will need to have a file called
'/WEB-INF/test-servlet.xml' in your application; this file will contain all of
your Spring Web MVC-specific components (beans).
 The WebApplicationContext is an extension of the plain
ApplicationContext that has some extra features necessary for web
applications.
 The Spring DispatcherServlet has a couple of special beans it uses in order
to be able to process requests and render the appropriate views. These
beans are included in the Spring framework and can be configured in the
WebApplicationContext
test-servlet.xml file
 test-servlet.xml file contains viewResolver , Handler mappings

and Controllers.
 viewResolver :

All controllers in the Spring Web MVC framework return a


ModelAndView instance.
 Views in Spring are addressed by a view name and are

resolved by a view resolver. For Example : if your controller


return new ModelAndView("empform"); means control
forwared to "/WEB-INF/jsp/empform.jsp" based on below
configuration.
When returning "empform" as a viewname, this view resolver
will hand the request over to the RequestDispatcher that will
send the request to /WEB-INF/jsp/empform.jsp.
BeanNameUrlHandlerMapping
A very simple, but very powerful handler mapping is the
BeanNameUrlHandlerMapping, which maps incoming HTTP requests to
names of beans, defined in the web application context.
<bean id="defaultHandlerMapping"
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

Controllers :
<bean name="/test/empform.do" class="com.EmpFormController"/>
<bean name="/test/saveempform.do" class="com.EmpSaveController"/>

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">


<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
If in the browser you call http://localhost:8080/springtest/test/empform.do
then EmpFormController class will be called.
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class EmpSaveController implements Controller
{
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out.println("inside EmpSaveController");
String firstName = request.getParameter("firstName");
System.out.println("firstName"+firstName);
String lastName = request.getParameter("lastName");
System.out.println("lastName"+lastName);
return new ModelAndView("success");
//RequestDispatcher that will send the request to /WEB-INF/jsp/success.jsp
} }

empform.jsp :
<form method="POST" action="/springtest/test/saveempform.do">
First Name:
<input name="firstName" type="text" value=""/>
Last Name:
<input name="lastName" type="text" value=""/>
<input type="submit" value="Save Changes" />
</form>
success.jsp :
<h2>Emp name saved </h2>
SimpleUrlHandlerMapping
The "/test/logonPage.do" call the logonController.
<bean id="urlMapping"
class="org.springframework.web.servlet.handler. SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/test/logonPage.do"><ref bean="logonController"/></entry>
</map>
</property>
</bean>
Controllers :
<bean id="logonController" class="com.LogonController">
<property name="sessionForm"> <value>true</value> </property>
<property name="commandName"> <value>userBean</value> </property>
<property name="commandClass"> <value>com.UserBean</value> </property>
<property name="validator"> <ref bean="logonFormValidator"/> </property>
<property name="formView"> <value>logonForm</value> </property>
<property name="successView"> <value>success</value> </property>
</bean>
In the above configuation
<property name="sessionForm"><value>true</value></property>
Keep command object throughout session
validator:
<bean id="logonFormValidator" class="com.LogonFormValidator"/>
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
public class LogonController extends SimpleFormController
{
public Object formBackingObject(HttpServletRequest request) throws ServletException
{
UserBean backingObject = new UserBean();
System.out.println("formBackingObject");
/* The backing object should be set up here, with data for the initial values
* of the form’s fields. This could either be hard-coded, or retrieved from a
* database.
*/
return backingObject;
}
public ModelAndView onSubmit(Object command) throws ServletException
{
UserBean user = (UserBean)command;
System.out.println("username :"+user.getUserName());
System.out.println("password :"+user.getPassword());
//Now you can validate to database
return new ModelAndView("succes");
}
public class UserBean {
import org.springframework.validation.Errors; String userName;
import org.springframework.validation.Validator; String password;

/**
public class LogonFormValidator implements Validator { * @return Returns the password.
*/
public boolean supports(Class clazz) { public String getPassword() {
return password;
return clazz.equals(UserBean.class); }
} /**
* @param password The password to set.
*/
public void validate(Object obj, Errors errors) { public void setPassword(String password) {
UserBean user = (UserBean) obj; this.password = password;
if (user == null)
null) { }
/**
errors.rejectValue("username", "error.login.not-specified", null,
null, * @return Returns the userName.
"Value required."); */
} else { public String getUserName() {
return userName;
}
if (user.getUserName() == null /**
|| user.getUserName().trim().length() <= 0) { * @param userName The userName to set.
*/
System.out
System.out.println("user
.println("user name null value"); public void setUserName(String userName) {
errors.rejectValue("userName", "error.login.invalid-user", this.userName = userName;
null, "Username is Required."); }
}
} else {
if (user.getPassword() == null
|| user.getPassword().trim().length() <= 0) {
errors.rejectValue("password", "error.login.invalid-pass",
null, "Password is Required.");
}
}

}
}
}
logonForm.jsp
<%@ taglib prefix="core" uri="http://java.sun.com/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt"%>
<%@ taglib prefix="str"
uri="http://jakarta.apache.org/taglibs/string-1.1"%>
<%@ taglib prefix="spring" uri="/spring"%>
Success.jsp:
<html><head><title>techfaq360 Spring Validation Example</title>
</head><body><center> <h2>Login Success </h2>
<h1>techfaq360 Spring Validation Example</h1>
<br />
<form method="post" action="/springvalidation/test/logonPage.do">
<table width="25%" border="1">
<tr><td align="center" bgcolor="lightblue">Log on</td>
</tr><tr><td>
<table border="0" width="100%">
<tr>
<td width="33%" align="right">Username:</td>
<td width="66%" align="left">
<spring:bind path="userBean.userName">
<input type="text" name="userName"
value="<core:out value="${status.value}"/>" />
</spring:bind></td>
</tr><tr>
<td colspan="2" align="center">
<spring:hasBindErrors name="userBean">
<font color="red"><core:out value="${status.errorMessage}" /></font>
</spring:hasBindErrors></td>
</tr><tr>
<td width="33%" align="right">Password:</td>
<td width="66%" align="left">
<spring:bind path="userBean.password">
<input type="password" name="password" />
</spring:bind></td>
</tr><tr>
<td colspan="2" align="center">
<spring:hasBindErrors name="userBean">
<font color="red"><core:out value="${status.errorMessage}" /></font>
</spring:hasBindErrors></td>
</tr>
<tr>
<td align="center" colspan="2"><input type="submit"
alignment="center" value="Submit"></td>
</tr>
</table></td></tr>
</table></form></center></body></html>
MultiActionController
<bean id="viewResolver"
id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
> MultiActionController class provides us a
<property name="prefix"
name="prefix">> functionality that allow to bind the multiple request-
<value>/WEB-INF/jsp
<value>/WEB-INF/jsp/</value>
/</value> handling methods in a single controller. The
</property>
MultiActionController used MethodNameResolver or
<property name="suffix"
name="suffix">
>
<value>.jsp
<value>.jsp</value>
</value> ParameterMethodNameResolver to find which
</property> method to be call when handling an incoming
</bean> request.
<bean name="/*.html"
name="/*.html" class=“com.MultiActionControllerExample"
class=“com.MultiActionControllerExample" />
</beans>
Index.jsp
<%@page contentType="text/html"
contentType="text/html" pageEncoding="UTF-8"
pageEncoding="UTF-8"%>
%>
<html>
<head>
<title>Multi
<title>Multi Action Controller Example</title>
</head>
<body>
<h4>Multi
<h4>Multi Action Controller Example</h4>
<a href="add.html"
href="add.html" >Add</a> <br/>
<a href="update.html"
href="update.html" >Update</a><br/>
<a href="edit.html"
href="edit.html" >Edit</a> <br/>
<a href="remove.html"
href="remove.html" >Remove</a>
</body>
</html>
showmessage.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html><head>
<title>Success Page</title>
</head>
<body>
${message}
</body>
</html>
package com;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class MultiActionControllerExample extends MultiActionController {
  
  public ModelAndView add(HttpServletRequest request,
      HttpServletResponse response) throws Exception {
      return new ModelAndView("showmessage", "message", "Add method called");
  }  
  public ModelAndView update(HttpServletRequest request,
      HttpServletResponse response) throws Exception {
      return new ModelAndView("showmessage", "message", "Update method called");
  }
  public ModelAndView edit(HttpServletRequest request,
      HttpServletResponse response) throws Exception {
      return new ModelAndView("showmessage", "message", "Edit method called");
  }
  public ModelAndView remove(HttpServletRequest request,
      HttpServletResponse response) throws Exception {
      return new ModelAndView("showmessage", "message", "Remove method called");
  }
}
Spring Hibernate
<beans>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/>
<property name="username" value="sa"/>
<property name="password" value="sa"/>
</bean>

<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">


<property name="dataSource" ref="myDataSource"/>
<property name="mappingResources">
<list>
<value>emp.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.HSQLDialect
</value>
</property>
</bean>

</beans>
The HibernateTemplate class provides many
methods that mirror the methods exposed on
the Hibernate Session interface.
Define DAO object and inject Session Factory.
<beans>
<bean id="empDao" class="com.techfaq.EmpDAO">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
</beans>

EmpDAO.java class
public class EmpDAO {

private HibernateTemplate hibernateTemplate;

public void setSessionFactory(SessionFactory sessionFactory)


{
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}

public Collection getEmpByDept(String dept) throws DataAccessException


{
return this.hibernateTemplate.find("from com.bean.Emp e where e.dept=?", dept);
}
}
HibernateDaoSupport
HibernateDaoSupport base class offers methods to access the current transactional Session. EmpDAO.java class
public class EmpDAO extends HibernateDaoSupport {

public Collection getEmpByDept(String dept) throws DataAccessException, MyException {


Session session = getSession(false);
try {
Query query = session.createQuery("from com.bean.Emp e where e.dept=?");
query.setString(0, dept);
List result = query.list();
if (result == null) {
throw new MyException("No results.");
}
return result;
}
catch (HibernateException ex) {
throw convertHibernateAccessException(ex);
}
}
}
Inheritence
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="parent" class="mybean" >
        <property name="name" value="Roseindia.net"/>
    </bean>
    <bean id="child" class="mybean" parent="parent">
        <property name="address" value="Rohini"/>
    </bean>
    <bean id="subchild" class="mybean" parent="parent"/>
</beans>
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ClassPathResource;
public class Main {
public class Main {
  public static void 
  public static void main(String[] args) 
main(String[] args) throws 
throws Exception {
Exception {
    XmlBeanFactory bf = new 
    XmlBeanFactory bf = new XmlBeanFactory(
XmlBeanFactory(new 
new ClassPathResource("context.xml"));
ClassPathResource("context.xml"));
    System.out.println("===============Inheritance demo=================");
    System.out.println(bf.getBean("child"));
    System.out.println(bf.getBean("subchild"));
    
  }
}
class mybean {
class mybean {
  private 
  private String name;
String name;
  private 
  private String address;
String address;
  public void 
  public void setName(String name) {
setName(String name) {
      this
      this.name = name;
.name = name;
  }
    public void 
    public void setAddress(String address) {
setAddress(String address) {
        this
        this.address = address;
.address = address;
    }
 
  @Override
  public 
  public String toString() {
String toString() {
      final 
      final StringBuilder stringBuilder = 
StringBuilder stringBuilder = new 
new StringBuilder();
StringBuilder();
      stringBuilder.append("Bean");
      stringBuilder.append("{name='").append(name).append('\'');
      stringBuilder.append(", address=").append(address);
     
      stringBuilder.append('}');
      return 
      return stringBuilder.toString();
stringBuilder.toString();
  }
}

Output:
Nov 25, 2008 3:39:29 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReade
r loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [context.xml]
===============Inheritance demo=================
Bean{name='Roseindia.net', address=Rohini}
Bean{name='Roseindia.net', address=null}
BUILD SUCCESSFUL (total time: 1 second)
Property injection
<?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"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="mybean" 
          class="Inject"
          p:name="Girish" 
          p:age="24" 
          p:address="Noida" 
          p:company="Roseindia.net" 
          p:email="girish@roseindia.net"/>
</beans>
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ClassPathResource;
public class Main {
public class Main {
    public static void 
    public static void main(String[] args) {
main(String[] args) {
        XmlBeanFactory beanFactory = new 
        XmlBeanFactory beanFactory = new XmlBeanFactory(
XmlBeanFactory(new 
new ClassPathResource(
ClassPathResource(
                "context.xml"));
        Inject demo = (Inject) beanFactory.getBean("mybean");
        System.out.println(demo);
    }
}
class Inject {
class Inject {
    private 
    private String name;
String name;
    private int 
    private int age;
age;
    private 
    private String company;
String company;
    private 
    private String email;
String email;
    private 
    private String address;
String address;
    public void 
    public void setAddress(String address) {
setAddress(String address) {
        this
        this.address = address;
.address = address;
    }
    public void 
    public void setCompany(String company) {
setCompany(String company) {
        this
        this.company = company;
.company = company;
    }
    public void 
    public void setEmail(String email) {
setEmail(String email) {
        this
        this.email = email;
.email = email;
    }
    public void 
    public void setAge(
setAge(int 
int age) {
age) {
        this
        this.age = age;
.age = age;
    }
    public void 
    public void setName(String name) {
setName(String name) {
        this
        this.name = name;
.name = name;
    }
    @Override
    public 
    public String toString() {
String toString() {
        return 
        return String.format("Name: %s\n" +
String.format("Name: %s\n" +
                "Age: %d\n" +
                "Address: %s\n" +
                "Company: %s\n" +
                "E-mail: %s",
                this
                this.name, 
.name, this
this.age, 
.age, this
this.address, 
.address, this
this.company, 
.company, this
this.email);
.email);
    }
}
This controller is use to redirect the page in the Spring 2.5 Web MVC applications. This controller doesn't 
require controller class. This controller provides an alternative to sending a request straight to a view such
as a JSP. we will configure just declared the ParameterizableViewController bean and set the view name
through the "viewName" property.
Now we will used ParameterizedViewController  for control the behavior of the application.
Example:
1) index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<a href="parameterizableviewcontroller.html">ParameterizableViewController Example</a>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" >
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" >
<property name="mappings">
<props>
<prop key="/parameterizableviewcontroller.html">parameterizableController</prop>
</props>
</property>
</bean>

<bean name="parameterizableController“
class="org.springframework.web.servlet.mvc.ParameterizableViewController" >
<property name="viewName" value="ParameterizableController" />
</bean>

<bean id="viewResolver“ class="org.springframework.web.servlet.view.InternalResourceViewResolver" >


<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
UMLFilenameViewController
If user don't want to include any logical operation on request and redirect to some resource then user used 
UrlFilenameViewController that's transform the virtual path of a URL into a view name and provide a view to display as a
user interface. In this example we will discuss about UrlFileNameViewController.

<?xml version="1.0"
version="1.0" encoding="UTF-8"
encoding="UTF-8"?>?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" >

<bean id="
id="staticViewController"
staticViewController" class="org.springframework.web.servlet.mvc.
class="org.springframework.web.servlet.mvc.UrlFilenameViewController
UrlFilenameViewController""/>

<bean id="urlMapping“
id="urlMapping“ class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
>
<property name="interceptors"
name="interceptors"> >
<list>
<ref local="localeChangeInterceptor"
local="localeChangeInterceptor"/>
/>
</list>
</property>
<property name="urlMap"
name="urlMap"> >
<map>
<entry key="/*.html"
key="/*.html"> >
<ref bean="
bean="staticViewController"
staticViewController"/>
</entry>
</map>
</property>
</bean>

<bean id="viewResolver“
id="viewResolver“ class="org.springframework.web.servlet.view.InternalResourceViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
>
<property name="prefix"
name="prefix">>
<value>/WEB-INF/</value>
</property>
<property name="suffix"
name="suffix">>
<value>.jsp
<value>.jsp</value>
</value>
</property>
</bean>
Index.jsp
<html>
<head></head>
<body>
<h3>UrlFileNameViewController Example</h3>
<h4><a href="MyAddress.html">My Home Address</a></h4><br/>
<h4><a href="MyOfficeAddress.html">My Office Address</a></h4>
</body>
</html>
AbstractWizardFormController
 Spring Web MVC provides AbstractWizardFormController class that handle wizard form. In this tutorial, we will used
AbstractWizardFormController class. The AbstractWizardFormController class provide us to store and show the forms
data with multiple pages. It manage the navigation between pages and validate the user input data form a single page of the
whole model object at once. In this tutorial we will discuss about this controller.

index.jsp
<%@page contentType="text/html"
contentType="text/html" pageEncoding="UTF-8"
pageEncoding="UTF-8"%>
%>
<html><head>
<title>AbstractWizardFormController Example</title>
</head><body>
<center>
<a href="user1.html">
AbstractWizardFormController Test Application</a><br/>
</center></body></html>
<?xml version="1.0"
version="1.0" encoding="UTF-8"
encoding="UTF-8"?>
?>
<beans xmlns="
xmlns="http://www.springframework.org/schema/beans "
xmlns:xsi="
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance "
xsi:schemaLocation= "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd "
xmlns:p= "http://www.springframework.org/schema/p" >

<bean id="urlMapping“
id="urlMapping“ class="
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping ">
<property name="interceptors">
<list> <ref local="localeChangeInterceptor" /> </list>
</property>
<property name="urlMap"
name="urlMap"> >
<map>
<entry key= "/user1.html">
<ref bean= "wizardController"
wizardController"/></entry>
</map>
</property></bean>

<bean id="wizardController" class=“com.AWizardFormController ">


<property name="commandName"><value>user</value></property>
<property name="commandClass"
name="commandClass"><value>net.roseindia.web.User</value></property>
><value>net.roseindia.web.User</value></property>
<property name="pages"><value>user1,user2,user3</value></property>
<property name="pageAttribute"
name="pageAttribute"><value>page</value></property>
><value>page</value></property>
</bean>

<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" >


<property name="paramName"
name="paramName" value="hl"
value="hl"/>
/>
</bean>

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />

<bean id="viewResolver“
id="viewResolver“ class=
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
"org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/ jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

</beans>
User1.jsp User2.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
pageEncoding="ISO-8859-1"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<html><head><title>First Entry</title></head> <html><head><title>Second Entry</title></head>
<body> <body>
<form:form method="POST" commandName="user">
<form:form method="POST" commandName="user">
<center><table><tr><td align="right" width="20%">
<strong>First Name:</strong></td><td style="width: 20%"> <center><table><tr><td align="right" width="20%">
<spring:bind path="user.firstName"> <strong>Date of birth:</strong></td><td style="width: 50%">
<input type="text" name="firstName" value="<c:out value="${status.value}"/>"/> <spring:bind path="user.dob">
</spring:bind></td><td><font color="red">
<form:errors path="firstName"/></font></td></tr><tr><td align="right" <input type="text" name="dob" value="<c:out value="${status.value}"/>"/>
width="20%"> </spring:bind></td><td><font color="red">
<strong>Last Name:</strong></td><td style="width: 20%">
<form:errors path="dob"/></font></td></tr><tr><td align="right" width="20%">
<spring:bind path="user.lastName">
<input type="text" name="lastName" value="<c:out value="${status.value}"/>"/> <strong>Address:</strong></td><td style="width: 50%">
</spring:bind></td><td><font color="red"> <spring:bind path="user.address">
<form:errors path="lastName"/></font></td></tr><tr> <input type="text" name="address" value="<c:out value="${status.value}"/>"/>
<td align="right" width="20%">
<strong>Email Id:</strong></td><td style="width: 40%"> </spring:bind></td><td>
<spring:bind path="user.emailId"> <font color="red"><form:errors path="address"/></font></td></tr><tr><td align="right"
<input type="text" name="emailId" value="<c:out value="${status.value}"/>"/> width="20%">
</spring:bind></td><td><font color="red"> <strong>Country:</strong></td><td style="width: 50%">
<form:errors path="emailId"/></font></td></tr><tr><td align="right"
width="20%"> <spring:bind path="user.country">
<strong>Contact:</strong></td><td style="width: 40%"> <input type="text" name="country" value="<c:out value="${status.value}"/>"/>
<spring:bind path="user.contact"> </spring:bind></td><td><font color="red">
<input type="text" name="contact" value="<c:out value="${status.value}"/>"/>
</spring:bind></td><td><font color="red"> <form:errors path="country"/></font></td></tr><tr><td align="right" width="20%">
<form:errors path="contact"/></font></td></tr><tr><td align="right" width="20%"> <strong>Qualification:</strong></td><td style="width: 50%">
<strong>Gender:</strong></td><td style="width: 40%"> <spring:bind path="user.qualification">
<spring:bind path="user.gender">
<input type="text" name="qualification" value="<c:out value="${status.value}"/>"/>
<input type="text" name="gender" value="<c:out value="${status.value}"/>"/>
</spring:bind></td><td><font color="red"> </spring:bind></td><td><font color="red">
<form:errors path="gender"/></font></td></tr><tr><td ><strong></strong></td> <form:errors path="qualification"/></font></td></tr><tr><td ></td><td style="width: 50%" >
<td colspan="2"> <input type="submit" name="_target0" value="Previous"/>
<input type="submit" name="_cancel" value="Cancle"/>
<input type="submit" name="_target1" value="Next"/> <input type="submit" name="_target2" value="Next"/>
<input type="submit" name="_target2" value="Finish"/></td></tr> <input type="submit" name="_cancel" value="Cancle"/>
</table></center></form:form> <input type="submit" name="_target2" value="Finish"/></td></tr></table>
</body></html>
</center></form:form></body></html>
public class User {
public class User {
  
  private 
  private String firstName;
String firstName;
  private 
  private String lastName;
String lastName;
User3.jsp   private 
  private String emailId;
  private 
String emailId;
  private String contact;    
String contact;    
<%@ page language="java" contentType="text/html;   private 
  private String gender;
  
String gender;

charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>   private 


  private String dob;
String dob;
  private 
  private String address;
String address;
<%@ taglib prefix="form"   private 
  private String country;
String country;

uri="http://www.springframework.org/tags/form"%>   private 
  private String qualification;
    
String qualification;

<%@ taglib prefix="spring"   public void 


  public void setFirstName(String firstName){
    this
setFirstName(String firstName){
    this.firstName = firstName;
.firstName = firstName;
uri="http://www.springframework.org/tags"%>   }
  public 
  public String getFirstName(){
String getFirstName(){
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>     return 
    return firstName;
  }
firstName;

<html><head><title>Show Details</title></head>   public void 


  public void setLastName(String lastName){
    this
setLastName(String lastName){
    this.lastName = lastName;
.lastName = lastName;
<body>   }
  public 
  public String getLastName(){
String getLastName(){
<form:form method="POST" commandName="user">     return 
    return lastName;
lastName;
  }
<center><table><tr><td style="width: 56%" colspan="2">   public void 
  public void setEmailId(String emailId){
setEmailId(String emailId){
    this
    this.emailId = emailId;
.emailId = emailId;
<strong>The Values entered are as   }

follow</strong></td></tr><tr><td align="right"   public 


  public String getEmailId(){
    return 
String getEmailId(){
    return emailId;
emailId;
width="20%">   }
  public void 
  public void setContact(String contact){
setContact(String contact){
<strong>First Name:</strong></td><td style="width: 56%">     this
    this.contact = contact;
  }
.contact = contact;

${user.firstName}</td></tr><tr><td align="right"   public 


  public String getContact(){
    return 
String getContact(){
    return contact;
contact;
width="20%">   }
  public void 
  public void setAddress(String address){
setAddress(String address){
<strong>Last Name:</strong></td><td style="width: 56%">     this
    this.address = address;
.address = address;
  }
${user.lastName}</td></tr><tr><td align="right"   public 
  public String getAddress(){
String getAddress(){
width="20%">     return 
    return address;
  }
address;

<strong>Email Id:</strong></td><td style="width: 56%">   public void 


  public void setGender(String gender){
    this
setGender(String gender){
    this.gender = gender;
.gender = gender;
${user.emailId}</td></tr><tr><td align="right" width="20%">   }
  public 
  public String getGender(){
String getGender(){
<strong>Contact:</strong></td><td style="width: 56%">     return 
    return gender;
  }
gender;

${user.contact}</td></tr><tr><td align="right" width="20%">   public void 


  public void setDob(String dob){
    this
setDob(String dob){
    this.dob = dob;
.dob = dob;
<strong>Gender:</strong></td><td style="width: 56%">   }
  public 
  public String getDob(){
String getDob(){
${user.gender}</td></tr><tr><td align="right" width="20%">     return 
    return dob;
  }
dob;

<strong>Date of Birth:</strong></td><td style="width: 56%">   public void 


  public void setCountry(String country){
    this
setCountry(String country){
    this.country = country;
.country = country;
${user.dob}</td></tr><tr><td align="right" width="20%">   }
  public 
  public String getCountry(){
String getCountry(){
<strong>Address:</strong></td><td style="width: 56%">     return 
    return country;
country;
  }
${user.address}</td></tr><tr><td align="right" width="20%">   public void 
  public void setQualification(String qualification){
setQualification(String qualification){
    this
    this.qualification = qualification;
.qualification = qualification;
<strong>Country:</strong></td><td style="width: 56%">   }
  public 
  public String getQualification(){
String getQualification(){
${user.country}</td></tr><tr><td align="right" width="20%">     return 
    return qualification;
qualification;
  }
<strong>Qualification:</strong></td><td style="width: 56%"> }

${user.qualification}</td></tr></table></center>
</form:form></body></html>
import java.util.regex.Matcher; if (b != true)
true) {
import java.util.regex.Pattern; errors.rejectValue("emailId", "error.is.not.valid",
"Email ID does not Valid ");
import javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletRequest; }
import javax.servlet.http.HttpServletResponse;
javax.servlet.http.HttpServletResponse; }
import org.springframework.validation.BindException;
org.springframework.validation.BindException; if (user.getContact() == "") {
import org.springframework.validation.Errors;
org.springframework.validation.Errors; errors.rejectValue("contact", "error.too-high", null,
null,
import org.springframework.web.servlet.ModelAndView;
org.springframework.web.servlet.ModelAndView; "Contact cannot be empty.");
import org.springframework.web.servlet.mvc.AbstractWizardFormController;
org.springframework.web.servlet.mvc.AbstractWizardFormController; }
import org.springframework.web.servlet.view.RedirectView;
org.springframework.web.servlet.view.RedirectView;
import net.roseindia.web.User;
net.roseindia.web.User; if ((user.getContact() != "") || (user.getContact().length()) != 0) {
Pattern pattern = Pattern.compile
Pattern.compile("\\d{1}-\\d{4}-\\d{6}");
("\\d{1}-\\d{4}-\\d{6}");
public class AWizardFormController extends AbstractWizardFormController { Matcher matcher = pattern.matcher(user.getContact());
boolean con = matcher.matches();
@Override if (con != true)
true) {
protected ModelAndView processCancel(HttpServletRequest
processCancel(HttpServletRequest request, errors.rejectValue("contact", "error.is.not.valid",
HttpServletResponse response, Object command, BindException errors) "Enter Contact Number Like 0-9999-999999");
throws Exception { }
// Logical code }
System.out
System.out.println("processCancel");
.println("processCancel");
return new ModelAndView( if (user.getGender() == "") {
ModelAndView(new RedirectView("user1.html"));
RedirectView("user1.html"));
} errors.rejectValue("gender", "error.too-high", null,
null,
"Gender cannot be empty.");
}
@Override
}
protected ModelAndView processFinish(HttpServletRequest
processFinish(HttpServletRequest request,
if (page == 1) {
HttpServletResponse response, Object command, BindException errors)
if (user.getDob() == "") {
throws Exception {
errors.rejectValue("dob", "error.too-high", null,
null,
// Logical code
"Date of birth cannot be empty.");
System.out
System.out.println("processFinish");
.println("processFinish");
}
return new ModelAndView(
ModelAndView(new RedirectView("user4.html"));
RedirectView("user4.html"));
if ((user.getDob() != "") || (user.getDob().length()) != 0) {
Pattern pattern = Pattern.compile
Pattern.compile("\\d{2}/\\d{2}/\\d{4}");
("\\d{2}/\\d{2}/\\d{4}");
}
Matcher matcher = pattern.matcher(user.getDob());
boolean DOB = matcher.matches();
protected void validatePage(Object command, Errors errors, int page) {
if (DOB != true)
true) {
User user = (User
(User)) command; errors.rejectValue("dob", "error.is.not.valid",
"Enter Date of birth Like 01/02/1986 ");
if (page == 0) { }
if (user.getFirstName() == "") { }
errors.rejectValue("firstName", "error.too-high", null,
null, if (user.getAddress() == "") {
"First Name cannot be empty."); errors.rejectValue("address", "error.too-high", null,
null,
} "Address cannot be empty.");
if (user.getLastName() == "") { }
errors.rejectValue("lastName", "error.too-high", null,
null, if (user.getCountry() == "") {
"Last Name cannot be empty."); errors.rejectValue("country", "error.too-high", null,
null,
} "Country cannot be empty.");
if (user.getEmailId() == "") { }
errors.rejectValue("emailId", "error.too-high", null,
null, if (user.getQualification() == "") {
"EmailId cannot be empty."); errors.rejectValue("qualification", "error.too-high", null,
null,
} "Qualification cannot be empty.");
if ((user.getEmailId() != "") || (user.getEmailId().length()) != 0) { }
Pattern p = Pattern.compile
Pattern.compile(".+@.+\\.[a-z]+");
(".+@.+\\.[a-z]+"); }
Matcher m = p.matcher(user.getEmailId()); }
boolean b = m.matches(); }
SimpleFromController
Spring provides SimpleFromController for control a form data in the web application. If you want to handle form in spring then
you need to use SimpleFormController by extending these in your Controller class. It's provides formView, successView in
the case of valid submission and provide validation errors if wrong data entry by the user in the form data. This is also handle
model object for binding and fetching data. In this example we will discuss about SimpleFormController work flow. In this
example we will create a form that accept user data and display

Index.jsp
<%@page contentType="text/html"
contentType="text/html" pageEncoding="UTF-8"
pageEncoding="UTF-8"%>
%>
<html><head><title>User Welcome Page</title></head>
<body bgcolor="#EEEEEE">
<center>
<a href="user.html">Fill User Personal Details</a>
</center></body></html>
<?xml version="1.0"
version="1.0" encoding="UTF-8"
encoding="UTF-8"?>
?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns="http://www.springframework.org/schema/beans" <bean id="userController"
id="userController" class="net.roseindia.web.UserFormController"
class="net.roseindia.web.UserFormController">
>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<property name="sessionForm"
name="sessionForm"> >
xsi:schemaLocation="http://www.springframework.org/schema/beans
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" <value>false</value>
xmlns:p="http://www.springframework.org/schema/p"
xmlns:p="http://www.springframework.org/schema/p">> </property>
<property name="commandName"
name="commandName"> >
<bean id="viewResolver“
id="viewResolver“ class="org.springframework.web.servlet.view.
class="org.springframework.web.servlet.view. <value>user</value>
InternalResourceViewResolver">
InternalResourceViewResolver">
<property name="prefix"
name="prefix">> </property>
<value>/WEB-INF/jsp/</value> <property name="commandClass"
name="commandClass"> >
</property> <value>net.roseindia.web.User</value>
<property name="suffix"
name="suffix">
> </property>
<value>.jsp</value>
<property name="validator"
name="validator">>
</property>
</bean> <ref bean="userValidator"
bean="userValidator" />
</property>
<bean id="urlMapping"
id="urlMapping" <property name="formView"
name="formView"> >
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMa
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMa <value>user</value>
pping">
pping"> </property>
<property name="interceptors"
name="interceptors">> <property name="successView"
name="successView"> >
<list>
<value>usersuccess</value>
<ref local="localeChangeInterceptor"
local="localeChangeInterceptor" />
</list> </property>
</property> </bean>
<property name="urlMap"
name="urlMap"> >
<map>
<bean id="localeChangeInterceptor"
id="localeChangeInterceptor"
<entry key="/user.html"
key="/user.html">
>
<ref bean="userController"
bean="userController" /> class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> >
</entry> <property name="paramName"
name="paramName" value="hl"
value="hl" />
</map> </bean>
</property> <bean id="localeResolver"
id="localeResolver"
</bean>
class="org.springframework.web.servlet.i18n.SessionLocaleResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
<bean id="userValidator"
id="userValidator" class="net.roseindia.web.UserValidator"
class="net.roseindia.web.UserValidator" /> </beans>
<tr>
<td>Date of birth:</td>

User.jsp <td>
<form:input path="dob"
path="dob" />
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %> </td>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <td>
<%@ taglib prefix="spring" uri="/spring"%> <font color="red"
color="red">>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <form:errors path="dob"
path="dob" />
</font>
<html>
</td>
<head> </tr>
<title>User Personal Details</title> <tr>
</head> <td>Qualification:</td>
<body> <td>
<center> <form:input path="qualification"
path="qualification" />
</td>
<h3>User Personal Details</h3>
<td>
<br /> <font color="red"
color="red">>
<form:form commandName="user"
commandName="user" method="POST"
method="POST" name="user"
name="user">
> <form:errors path="qualification"
path="qualification" />
<table border="0"
border="0">> </font>
<tr> </td>
<td>Name:</td> </tr>
<tr>
<td>
<td>Contact Number:</td>
<form:input path="name"
path="name" /> <td>
</td> <form:input path="contact"
path="contact" />
<td> </td>
<font color="red"
color="red">> <td>
<form:errors path="name"
path="name" /> <font color="red"
color="red">>
<form:errors path="contact"
path="contact" />
</font>
</font>
</td> </td>
</tr> </tr>
<tr> <tr>
<td>Email ID:</td> <td>Address:</td>
<td> <td>
<form:input path="address"
path="address" />
<form:input path="emailid"
path="emailid" />
</td>
</td> <td>
<td> <font color="red"
color="red">>
<font color="red"
color="red">> <form:errors path="address"
path="address" />
<form:errors path="emailid"
path="emailid" /> </font>
</font> </td>
</tr>
</td>
<tr>
</tr> <td colspan="3"
colspan="3" align="center"
align="center">
>
<input type="submit"
type="submit" value="Save"
value="Save" />
</td>
</tr>
</table>
</form:form>
</center>
</body>
</html>
userSuccess.jsp <tr>
<%@ page session="false"%>
<td>Qualification:</td>
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<td>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="spring" uri="/spring" %> <core:out value="${user.qualification}"
value="${user.qualification}" />
<html> </td>
<head> </tr>
<title>User Personal Details Display</title> <tr>
</head> <td>Contact Number:</td>
<body> <td>
<center> <core:out value="${user.contact}"
value="${user.contact}" />
<h3>User Personal Details Display</h3>
</td>
<br>
</tr>
<table>
<tr> <tr>
<td colspan="2"
colspan="2" align="center"
align="center">> <td>Address:</td>
<font size="5"
size="5">User
>User Information</font> <td>
</td> <core:out value="${user.address}"
value="${user.address}" />
</tr> </td>
<tr> </tr>
<td>Name:</td> </table>
<td>
<a href="user.html"
href="user.html">Back</a>
>Back</a>
<core:out value="${user.name}"
value="${user.name}" />
</center>
</td>
</tr> </body>
<tr> </html>
<td>Email ID:</td>
<td>
<core:out value="${user.emailid}"
value="${user.emailid}" />
</td>
</tr>
<tr>
<td>Date Of Birth:</td>
<td>
<core:out value="${user.dob}"
value="${user.dob}" />
</td>
</tr>
public class User {
public class User { package net.roseindia.web;
package net.roseindia.web;
   public User(){}
public User(){}
     private String name;     import javax.servlet.http.HttpServletRequest;
    private String emailid; import javax.servlet.ServletException;
import javax.servlet.ServletException;
    private String dob; import org.springframework.web.servlet.ModelAndView;
    private String address; import org.springframework.web.servlet.view.RedirectVi
import org.springframework.web.servlet.view.RedirectVi
    private String qualification; ew;
    private String contact; import org.springframework.web.servlet.mvc.SimpleFor
mController;
    public String getDob() {
public String getDob() {
        return 
        return dob;
    }
dob; import net.roseindia.web.User;
    public void 
    public void setDob(String dob) {
setDob(String dob) {
        this
        this.dob = dob;
    }
.dob = dob; @SuppressWarnings("deprecation")
    public 
    public String getQualification() {
String getQualification() { public class UserFormController
public class UserFormController  extends SimpleFormCo
extends SimpleFormCo
        return 
        return qualification;
    }
qualification; ntroller {
  
    public void 
    public void setQualification(String qualification) {
        this
setQualification(String qualification) {
        this.qualification = qualification;
.qualification = qualification;
  @Override
    }   protected 
  protected ModelAndView onSubmit(Object command) 
ModelAndView onSubmit(Object command) tt
    public 
    public String getContact() {
String getContact() {
        return 
        return contact;
contact;
hrows ServletException {
    }     User user = (User) command;    
    public void 
    public void setContact(String contact) {
setContact(String contact) {
    
        this
        this.contact = contact;
.contact = contact;     ModelAndView modelAndView = new ModelAndVie
    } w(getSuccessView());
    public 
    public String getName() {
String getName() {     modelAndView.addObject("user", user);
        return 
        return name;
name;
    }     return modelAndView;    
    }
    public void 
    public void setName(String name) {
setName(String name) {
        this
        this.name = name;
.name = name; }
    }
    public 
    public String getEmailid() {
String getEmailid() {
        return 
        return emailid;
emailid;
    }
    public void 
    public void setEmailid(String emailid) {
setEmailid(String emailid) {
        this
        this.emailid = emailid;
.emailid = emailid;
    }
    public 
    public String getAddress() {
String getAddress() {
        return 
        return address;
address;
    }
    public void 
    public void setAddress(String address) {
setAddress(String address) {
        this
        this.address = address;
.address = address;
    }
}
package net.roseindia.web;
net.roseindia.web; if ((user.getDob() != "") || (user.getDob().length()) != 0) {
Pattern pattern = Pattern.compile
Pattern.compile("\\d{2}/\\d{2}/\\d{4}");
("\\d{2}/\\d{2}/\\d{4}");
import java.util.regex.*; Matcher matcher = pattern.matcher(user.getDob());
import org.springframework.validation.Errors;
org.springframework.validation.Errors; boolean DOB = matcher.matches();
import org.springframework.validation.Validator;
org.springframework.validation.Validator; if (DOB != true)
true) {
import net.roseindia.web.User;
net.roseindia.web.User; errors.rejectValue("dob", "error.is.not.valid",
"Enter Date of birth Like 01/02/1986 ");
public class UserValidator implements Validator { }
}
@Override if (user.getName() == null || user.getName().length() == 0) {
public boolean supports(Class clazz) { errors.rejectValue("name", "error.empty.field", "Please Enter Name");
return User.
User.class.isAssignableFrom(clazz);
class.isAssignableFrom(clazz); }
} if (user.getDob() == null || user.getDob().length() == 0) {
errors.rejectValue("dob", "error.empty.field",
public void validate(Object obj, Errors errors) { "Please Enter Date Of Birth");
User user = (User
(User)) obj; }
if (user.getContact() == null || user.getContact().length() == 0) {
if ((user.getEmailid() != "") || (user.getEmailid().length()) != 0) { errors.rejectValue("contact", "error.empty.field",
Pattern p = Pattern.compile
Pattern.compile(".+@.+\\.[a-z]+");
(".+@.+\\.[a-z]+"); "Please Enter Contact Number");
Matcher m = p.matcher(user.getEmailid()); }
boolean b = m.matches(); if (user.getEmailid() == null || user.getEmailid().length() == 0) {
if (b != true)
true) { errors.rejectValue("emailid", "error.empty.field",
errors.rejectValue("emailid", "error.is.not.valid", "Please Enter Email ID");
"Email ID does not Valid "); }
if (user.getQualification() == null
}
|| user.getQualification().length() == 0) {
}
errors.rejectValue("qualification", "error.empty.field",
"Please Enter Qualification");
if ((user.getContact() != "") || (user.getContact().length()) != 0) {
}
Pattern pattern = Pattern.compile
Pattern.compile("\\d{1}-\\d{4}-\\d{6}");
("\\d{1}-\\d{4}-\\d{6}");
if (user.getAddress() == null || user.getAddress().length() == 0) {
Matcher matcher = pattern.matcher(user.getContact());
errors.rejectValue("address", "error.empty.field",
boolean con = matcher.matches();
"Please Enter Address");
if (con != true)
true) {
}
errors.rejectValue("contact", "error.is.not.valid",
}
"Enter Contact Number Like 0-9999-999999");
}
}
}
Sample
Sample
Sample
Sample
Sample
Sample
Sample
Sample
Spring Transaction Management
The key to the Spring transaction abstraction is the notion of a transaction
strategy. A transaction strategy is defined by the
org.springframework.transaction.PlatformTransactionManager interface:
public interface PlatformTransactionManager {
TransactionStatus getTransaction(TransactionDefinition definition)
throws TransactionException;
void commit(TransactionStatus status) throws TransactionException;
void rollback(TransactionStatus status) throws TransactionException;
}
This is primarily a service provider interface (SPI), although it can be used
programmatically from your application code. Because
PlatformTransactionManager is an interface, it can be easily mocked or
stubbed as necessary. It is not tied to a lookup strategy such as JNDI.
PlatformTransactionManager implementations are defined like any other
object (or bean) in the Spring Framework IoC container. This benefit alone
makes Spring Framework transactions a worthwhile abstraction even when
you work with JTA. Transactional code can be tested much more easily
than if it used JTA directly.
Again in keeping with Spring's philosophy, the TransactionException that
can be thrown by any of the PlatformTransactionManager interface's
methods is unchecked (that is, it extends thejava.lang.RuntimeException
class). Transaction infrastructure failures are almost invariably fatal. In rare
cases where application code can actually recover from a transaction
failure, the application developer can still choose to catch and handle
TransactionException. The salient point is that developers are not forced to
do so.

The getTransaction(..) method returns a TransactionStatus object,


depending on a TransactionDefinition parameter. The returned
TransactionStatus might represent a new transaction, or can represent an
existing transaction if a matching transaction exists in the current call
stack. The implication in this latter case is that, as with Java EE transaction
contexts, a TransactionStatus is associated with a thread of execution.
Transaction Denifition
The TransactionDefinition interface specifies:
• Isolation: The degree to which this transaction is isolated from the work of other transactions. For
example, can this transaction see uncommitted writes from other transactions?
• Propagation: Typically, all code executed within a transaction scope will run in that transaction.
However, you have the option of specifying the behavior in the event that a transactional method is
executed when a transaction context already exists. For example, code can continue running in the
existing transaction (the common case); or the existing transaction can be suspended and a new
transaction created. Spring offers all of the transaction propagation options familiar from EJB CMT.
To read about the semantics of transaction propagation in Spring, see the section called “Transaction
propagation”.
• Timeout: How long this transaction runs before timing out and being rolled back automatically by the
underlying transaction infrastructure.
• Read-only status: A read-only transaction can be used when your code reads but does not modify data.
Read-only transactions can be a useful optimization in some cases, such as when you are using
Hibernate.

These settings reflect standard transactional concepts. If necessary, refer to resources that discuss
transaction isolation levels and other core transaction concepts. Understanding these concepts is essential
to using the Spring Framework or any transaction management solution.
Transaction Status
The TransactionStatus interface provides a simple way for transactional code
to control transaction execution and query transaction status. The concepts
should be familiar, as they are common to all transaction APIs:
public interface TransactionStatus extends SavepointManager {
boolean isNewTransaction();
boolean hasSavepoint();
void setRollbackOnly();
boolean isRollbackOnly();
void flush();
boolean isCompleted();
}
Regardless of whether you opt for declarative or programmatic transaction
management in Spring, defining the correct PlatformTransactionManager
implementation is absolutely essential. You typically define this
implementation through dependency injection.
PlatformTransactionManager implementations normally require knowledge of the environment
in which they work: JDBC, JTA, Hibernate, and so on. The following examples show how you
can define a local PlatformTransactionManager implementation. (This example works with
plain JDBC.)
You define a JDBC DataSource
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-
method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
The related The PlatformTransactionManager bean definition will then have a reference to the
DataSource definition. It will look like this:
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
Hibernate TM
You can also use Hibernate local transactions easily, as shown in the following examples. In this case, you need
to define a Hibernate LocalSessionFactoryBean, which your application code will use to obtain Hibernate
Session instances.
The DataSource bean definition will be similar to the local JDBC example shown previously and thus is not
shown in the following example.
Note
If the DataSource, used by any non-JTA transaction manager, is looked up via JNDI and managed by a Java EE
container, then it should be non-transactional because the Spring Framework, rather than the Java EE
container, will manage the transactions. The txManager bean in this case is of the
HibernateTransactionManager type. In the same way as the DataSourceTransactionManager needs a
reference to the DataSource, the HibernateTransactionManager needs a reference to the SessionFactory.
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>org/springframework/samples/petclinic/hibernate/petclinic.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=${hibernate.dialect}
</value>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

You might also like