91
Spring Spring Ravikumar Maddi Ravikumar Maddi

Spring

Embed Size (px)

DESCRIPTION

Spring and Spring Transaction Management....

Citation preview

Page 1: Spring

Spring Spring

Ravikumar MaddiRavikumar Maddi

Page 2: Spring

MessageSourceMessageSource

Spring currently provides two MessageSource Spring currently provides two MessageSource implementations. These are the implementations. These are the ResourceBundleMessageSource and the ResourceBundleMessageSource and the StaticMessageSource. StaticMessageSource.

Page 3: Spring

ExampleExample<bean id="messageSource" <bean id="messageSource"

class="org.springframework.context.support.class="org.springframework.context.support.ResourceBundleMessageSourceResourceBundleMessageSource">"><property name="basenames"><property name="basenames"><list><list><value>applicationprop</value><value>applicationprop</value></list></list></property></property><bean><bean>

<!-- let's inject the above MessageSource into this POJO --><!-- let's inject the above MessageSource into this POJO --><bean id="example" class="com.techfaq.Example"><bean id="example" class="com.techfaq.Example"><property name="messages" ref="messageSource"/><property name="messages" ref="messageSource"/></bean> </bean>

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------public class Example {public class Example {

private MessageSource messages;private MessageSource messages;

public void setMessages(MessageSource messages) {public void setMessages(MessageSource messages) {this.messages = messages;this.messages = messages;}}

public void execute() {public void execute() {String message = String message = this.messages.getMessage("user.required",this.messages.getMessage("user.required",new Object [] {"UserName"}, "Required", null);new Object [] {"UserName"}, "Required", null);System.out.println(message);System.out.println(message);message = this.messages.getMessage("passwd.required",null, "Required", null);message = this.messages.getMessage("passwd.required",null, "Required", null);System.out.println(message);System.out.println(message);} }

}}

Page 4: Spring

applicationprop.properties file in classpath. applicationprop.properties file in classpath.

# in 'applicationprop.properties'# in 'applicationprop.properties'passwd.required=Password Required!passwd.required=Password Required!user.required= '{0}' is required.user.required= '{0}' is required.

out put is :out put is :Password Required!Password Required!UserName is required.UserName is required.

Page 5: Spring

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

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

    <bean id="encyclopedia"    <bean id="encyclopedia"          name="mybean"          name="mybean"                    classclass="Configure">="Configure">        <constructor-arg>        <constructor-arg>            <util:map>            <util:map>                <entry key="CompanyName" value="Roseindia.net"/>                <entry key="CompanyName" value="Roseindia.net"/>                <entry key="Address" value="Rohini"/>                <entry key="Address" value="Rohini"/>            </util:map>            </util:map>        </constructor-arg>        </constructor-arg>    </bean>    </bean>

    <bean id="company"     <bean id="company" classclass="Companyinformation">="Companyinformation">        <property name="encyclopedia" ref="mybean"/>        <property name="encyclopedia" ref="mybean"/>    </bean>    </bean></beans> </beans>

Page 6: Spring

public class public class Main {Main {

        public static void public static void main(String[] a) {main(String[] a) {        XmlBeanFactory beanFactory =         XmlBeanFactory beanFactory = new new XmlBeanFactory(XmlBeanFactory(new new ClassPathResource("context.xml"));ClassPathResource("context.xml"));

        company mycomp = (company) beanFactory.getBean("company");        company mycomp = (company) beanFactory.getBean("company");        System.out.println("Name of the company is: " + mycomp.Name());        System.out.println("Name of the company is: " + mycomp.Name());        System.out.println("Address of the company is: " + mycomp.address());        System.out.println("Address of the company is: " + mycomp.address());    }    }}}

interface interface company {company {

    String Name();    String Name();    String address();    String address();}}

interface interface Detail {Detail {

    String find(String entry);    String find(String entry);}}

class class Companyinformation Companyinformation implements implements company {company {

        private private Detail detail;Detail detail;

        public public String Name() {String Name() {        String name =         String name = thisthis.detail.find("CompanyName");.detail.find("CompanyName");                return return String.valueOf(name);String.valueOf(name);    }    }

        public public String address() {String address() {        String add =         String add = thisthis.detail.find("Address");.detail.find("Address");                return return String.valueOf(add);String.valueOf(add);    }    }

        public void public void setEncyclopedia(Detail d) {       setEncyclopedia(Detail d) {       thisthis.detail = d;    }.detail = d;    }}}class class Configure 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.");        Assert.notNull(map, "Arguments cannot be null.");                thisthis.map = map;.map = map;    }    }

        public public String find(String s) {String find(String s) {                return return (String) (String) thisthis.map.get(s);.map.get(s);    }    }} }

Page 7: Spring

In web.xml fileIn web.xml file <web-app><web-app>

<servlet><servlet> <servlet-name>test</servlet-name> <servlet-name>test</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> <load-on-startup>1</load-on-startup></servlet></servlet><servlet-mapping><servlet-mapping> <servlet-name>test</servlet-name> <servlet-name>test</servlet-name> <url-pattern>*.do</url-pattern> <url-pattern>*.do</url-pattern></servlet-mapping></servlet-mapping>

</web-app></web-app>

Spring MVCSpring MVC

Page 8: Spring
Page 9: Spring

With the above servlet configuration , you will need to have a file called With the above servlet configuration , you will need to have a file called '/WEB-INF/'/WEB-INF/testtest-servlet.xml' in your application; this file will contain all of -servlet.xml' in your application; this file will contain all of your Spring Web MVC-specific components (beans). your Spring Web MVC-specific components (beans).

The WebApplicationContext is an extension of the plain The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web ApplicationContext that has some extra features necessary for web applications.applications.

The Spring DispatcherServlet has a couple of special beans it uses in order 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 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 beans are included in the Spring framework and can be configured in the WebApplicationContextWebApplicationContext

Page 10: Spring

test-servlet.xml filetest-servlet.xml file test-servlet.xml file contains viewResolver , Handler mappings test-servlet.xml file contains viewResolver , Handler mappings

and Controllers.and Controllers. viewResolver :viewResolver :

All controllers in the Spring Web MVC framework return a All controllers in the Spring Web MVC framework return a ModelAndView instance. ModelAndView instance.

Views in Spring are addressed by a view name and are Views in Spring are addressed by a view name and are resolved by a view resolver. For Example : if your controller resolved by a view resolver. For Example : if your controller return new ModelAndView("empform"); means control return new ModelAndView("empform"); means control forwared to "/WEB-INF/jsp/empform.jsp" based on below forwared to "/WEB-INF/jsp/empform.jsp" based on below configuration. configuration. When returning "empform" as a viewname, this view resolver When returning "empform" as a viewname, this view resolver will hand the request over to the RequestDispatcher that will will hand the request over to the RequestDispatcher that will send the request to /WEB-INF/jsp/empform.jsp. send the request to /WEB-INF/jsp/empform.jsp.

Page 11: Spring

BeanNameUrlHandlerMappingBeanNameUrlHandlerMapping

A very simple, but very powerful handler mapping is the A very simple, but very powerful handler mapping is the BeanNameUrlHandlerMapping, which maps incoming HTTP requests to BeanNameUrlHandlerMapping, which maps incoming HTTP requests to names of beans, defined in the web application context.names of beans, defined in the web application context.<bean id="defaultHandlerMapping" <bean id="defaultHandlerMapping" class="org.springframework.web.servlet.handler.class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMappingBeanNameUrlHandlerMapping"/> "/>

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

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

</bean></bean>

If in the browser you call http://localhost:8080/springtest/test/empform.do If in the browser you call http://localhost:8080/springtest/test/empform.do then then EmpFormController EmpFormController class will be called. class will be called.

Page 12: Spring

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

public class EmpSaveController implements Controllerpublic class EmpSaveController implements Controller {{

public ModelAndView handleRequest(HttpServletRequest request, public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {HttpServletResponse response) throws Exception {

System.out.println("inside EmpSaveController");System.out.println("inside EmpSaveController");String firstName = request.getParameter("firstName");String firstName = request.getParameter("firstName");System.out.println("firstName"+firstName);System.out.println("firstName"+firstName);String lastName = request.getParameter("lastName");String lastName = request.getParameter("lastName");System.out.println("lastName"+lastName);System.out.println("lastName"+lastName);return new ModelAndView("success");return new ModelAndView("success");//RequestDispatcher that will send the request to /WEB-INF/jsp/success.jsp //RequestDispatcher that will send the request to /WEB-INF/jsp/success.jsp

}} } }

empform.jsp :empform.jsp :<form method="POST" action="/springtest/test/saveempform.do"><form method="POST" action="/springtest/test/saveempform.do">

First Name:First Name:<input name="firstName" type="text" value=""/><input name="firstName" type="text" value=""/>Last Name:Last Name:<input name="lastName" type="text" value=""/><input name="lastName" type="text" value=""/><input type="submit" value="Save Changes" /><input type="submit" value="Save Changes" /></form></form>

success.jsp :success.jsp :<h2>Emp name saved </h2><h2>Emp name saved </h2>

Page 13: Spring

SimpleUrlHandlerMappingSimpleUrlHandlerMapping

The "/test/logonPage.do" call the logonController.The "/test/logonPage.do" call the logonController.<bean id="urlMapping" <bean id="urlMapping" class="org.springframework.web.servlet.handler.class="org.springframework.web.servlet.handler.SimpleUrlHandlerMappingSimpleUrlHandlerMapping">"><property name="urlMap"><property name="urlMap"><map><map><entry key="/test/logonPage.do"><ref bean="logonController"/></entry><entry key="/test/logonPage.do"><ref bean="logonController"/></entry></map></map></property></property></bean></bean>Controllers Controllers : : <bean id="logonController" class="com.LogonController"><bean id="logonController" class="com.LogonController"><property name="sessionForm"> <value>true</value> </property> <property name="sessionForm"> <value>true</value> </property> <property name="commandName"> <value>userBean</value> </property><property name="commandName"> <value>userBean</value> </property><property name="commandClass"> <value>com.UserBean</value> </property> <property name="commandClass"> <value>com.UserBean</value> </property> <property name="validator"> <ref bean="logonFormValidator"/> </property><property name="validator"> <ref bean="logonFormValidator"/> </property><property name="formView"> <value>logonForm</value> </property><property name="formView"> <value>logonForm</value> </property><property name="successView"> <value>success</value> </property><property name="successView"> <value>success</value> </property></bean></bean>In the above configuation In the above configuation

<property name="sessionForm"><value>true</value></property> <property name="sessionForm"><value>true</value></property> Keep command object throughout session Keep command object throughout session validatorvalidator: : <bean id="logonFormValidator" class="com.LogonFormValidator"/> <bean id="logonFormValidator" class="com.LogonFormValidator"/>

Page 14: Spring

import javax.servlet.ServletException;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequest;

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

public class LogonController extends public class LogonController extends SimpleFormControllerSimpleFormController {{

public Object formBackingObject(HttpServletRequest request) throws ServletExceptionpublic Object formBackingObject(HttpServletRequest request) throws ServletException{{ UserBean backingObject = new UserBean(); UserBean backingObject = new UserBean(); System.out.println("formBackingObject"); System.out.println("formBackingObject");

/* The backing object should be set up here, with data for the initial values /* 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 * of the form’s fields. This could either be hard-coded, or retrieved from a * database. * database. */ */return backingObject;return backingObject;}}

public ModelAndView onSubmit(Object command) throws ServletException public ModelAndView onSubmit(Object command) throws ServletException {{

UserBean user = (UserBean)command; UserBean user = (UserBean)command; System.out.println("username :"+user.getUserName()); System.out.println("username :"+user.getUserName()); System.out.println("password :"+user.getPassword()); System.out.println("password :"+user.getPassword()); //Now you can validate to database //Now you can validate to database return new ModelAndView("succes"); return new ModelAndView("succes");} }

Page 15: Spring

importimport org.springframework.validation.Errors; org.springframework.validation.Errors;importimport org.springframework.validation.Validator; org.springframework.validation.Validator;

publicpublic classclass LogonFormValidator LogonFormValidator implementsimplements Validator { Validator {

publicpublic booleanboolean supports(Class clazz) { supports(Class clazz) {returnreturn clazz.equals(UserBean. clazz.equals(UserBean.classclass););

}}

publicpublic voidvoid validate(Object obj, Errors errors) { validate(Object obj, Errors errors) {UserBean user = (UserBean) obj;UserBean user = (UserBean) obj;ifif (user == (user == nullnull) {) {errors.rejectValue("username", "error.login.not-specified", errors.rejectValue("username", "error.login.not-specified", nullnull,,"Value required.");"Value required.");} } elseelse { {

ifif (user.getUserName() == (user.getUserName() == nullnull|| user.getUserName().trim().length() <= 0) {|| user.getUserName().trim().length() <= 0) {System.System.outout.println("user name null value");.println("user name null value");errors.rejectValue("userName", "error.login.invalid-user",errors.rejectValue("userName", "error.login.invalid-user",nullnull, "Username is Required.");, "Username is Required.");} } elseelse { {ifif (user.getPassword() == (user.getPassword() == nullnull|| user.getPassword().trim().length() <= 0) {|| user.getPassword().trim().length() <= 0) {errors.rejectValue("password", "error.login.invalid-pass",errors.rejectValue("password", "error.login.invalid-pass",nullnull, "Password is Required.");, "Password is Required.");}}}}

}}}}}}

public class UserBean {String userName;String password;

/*** @return Returns the password.*/public String getPassword() {return password;}/*** @param password The password to set.*/public void setPassword(String password) {this.password = password;}/*** @return Returns the userName.*/public String getUserName() {return userName;}/*** @param userName The userName to set.*/public void setUserName(String userName) {this.userName = userName;}}

Page 16: Spring

<%@ 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"%>

<html><head><title>techfaq360 Spring Validation Example</title></head><body><center><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>

logonForm.jsp

Success.jsp:

<h2>Login Success </h2>

Page 17: Spring

MultiActionControllerMultiActionController<bean id=<bean id="viewResolver""viewResolver"class=class="org.springframework.web.servlet.view.InternalResourceViewResolver""org.springframework.web.servlet.view.InternalResourceViewResolver">><property name=<property name="prefix""prefix">><value>/WEB-INF/<value>/WEB-INF/jspjsp/</value>/</value></property></property><property name=<property name="suffix""suffix">><value>.<value>.jspjsp</value></value></property></property></bean> </bean> <bean name=<bean name="/*.html""/*.html" class= class=“com.MultiActionControllerExample"“com.MultiActionControllerExample" /> /></beans></beans>Index.jspIndex.jsp<%@page contentType=<%@page contentType="text/html""text/html" pageEncoding= pageEncoding="UTF-8""UTF-8"%>%><html><html><head><head><title><title>MultiMulti Action Controller Example</title> Action Controller Example</title></head></head><body><body><h4><h4>MultiMulti Action Controller Example</h4> Action Controller Example</h4><a href=<a href="add.html""add.html" >Add</a> <br/> >Add</a> <br/><a href=<a href="update.html""update.html" >Update</a><br/> >Update</a><br/><a href=<a href="edit.html""edit.html" >Edit</a> <br/> >Edit</a> <br/><a href=<a href="remove.html""remove.html" >Remove</a> >Remove</a></body></body></html></html>showmessage.jspshowmessage.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"%><html><head><html><head><title>Success Page</title><title>Success Page</title></head></head><body><body>${message}${message}</body></body></html></html>

MultiActionController class provides us a MultiActionController class provides us a functionality that allow to bind the multiple request-functionality that allow to bind the multiple request-handling methods in a single controller. The handling methods in a single controller. The MultiActionController used MultiActionController used MethodNameResolverMethodNameResolver or or ParameterMethodNameResolverParameterMethodNameResolver to find which to find which method to be call when handling an incoming method to be call when handling an incoming request. request.

Page 18: Spring

package com;package com; import import javax.servlet.http.HttpServletRequest;javax.servlet.http.HttpServletRequest;

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

import import org.springframework.web.servlet.ModelAndView;org.springframework.web.servlet.ModelAndView;import import org.springframework.web.servlet.mvc.multiaction.MultiActionController;org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class public class MultiActionControllerExample MultiActionControllerExample extends extends MultiActionController {MultiActionController {        public public ModelAndView add(HttpServletRequest request,ModelAndView add(HttpServletRequest request,      HttpServletResponse response)       HttpServletResponse response) throws throws Exception {Exception {            return new return new ModelAndView("showmessage", "message", "Add method called");ModelAndView("showmessage", "message", "Add method called");  }    }      public public ModelAndView update(HttpServletRequest request,ModelAndView update(HttpServletRequest request,      HttpServletResponse response)       HttpServletResponse response) throws throws Exception {Exception {            return new return new ModelAndView("showmessage", "message", "Update method called");ModelAndView("showmessage", "message", "Update method called");  }  }    public public ModelAndView edit(HttpServletRequest request,ModelAndView edit(HttpServletRequest request,      HttpServletResponse response)       HttpServletResponse response) throws throws Exception {Exception {            return new return new ModelAndView("showmessage", "message", "Edit method called");ModelAndView("showmessage", "message", "Edit method called");  }  }    public public ModelAndView remove(HttpServletRequest request,ModelAndView remove(HttpServletRequest request,      HttpServletResponse response)       HttpServletResponse response) throws throws Exception {Exception {            return new return new ModelAndView("showmessage", "message", "Remove method called");ModelAndView("showmessage", "message", "Remove method called");  }  }} }

Page 19: Spring

Spring HibernateSpring Hibernate<beans><beans>

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"><bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"><property name="driverClassName" value="org.hsqldb.jdbcDriver"/><property name="driverClassName" value="org.hsqldb.jdbcDriver"/><property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/><property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/><property name="username" value="sa"/><property name="username" value="sa"/><property name="password" value="sa"/><property name="password" value="sa"/></bean></bean>

<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="dataSource" ref="myDataSource"/><property name="dataSource" ref="myDataSource"/><property name="mappingResources"><property name="mappingResources"><list><list><value>emp.hbm.xml</value><value>emp.hbm.xml</value></list></list></property></property><property name="hibernateProperties"><property name="hibernateProperties"><value><value>hibernate.dialect=org.hibernate.dialect.HSQLDialecthibernate.dialect=org.hibernate.dialect.HSQLDialect</value></value></property></property></bean></bean>

</beans> </beans>

Page 20: Spring

The HibernateTemplate class provides many The HibernateTemplate class provides many methods that mirror the methods exposed on methods that mirror the methods exposed on the Hibernate Session interface.the Hibernate Session interface.Define DAO object and inject Session Factory. Define DAO object and inject Session Factory.

Page 21: Spring

<beans><beans><bean id="empDao" class="com.techfaq.EmpDAO"><bean id="empDao" class="com.techfaq.EmpDAO"><property name="sessionFactory" ref="mySessionFactory"/><property name="sessionFactory" ref="mySessionFactory"/></bean></bean></beans></beans>

EmpDAO.java class EmpDAO.java class public class EmpDAO {public class EmpDAO {

private HibernateTemplate hibernateTemplate;private HibernateTemplate hibernateTemplate;

public void setSessionFactory(SessionFactory sessionFactory)public void setSessionFactory(SessionFactory sessionFactory){{

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

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

return this.hibernateTemplate.find("from com.bean.Emp e where e.dept=?", dept);return this.hibernateTemplate.find("from com.bean.Emp e where e.dept=?", dept);}}

}}

Page 22: Spring

HibernateDaoSupportHibernateDaoSupport HibernateDaoSupport base class offers methods to access the current transactional Session. EmpDAO.java class HibernateDaoSupport base class offers methods to access the current transactional Session. EmpDAO.java class public class EmpDAO extends HibernateDaoSupport {public class EmpDAO extends HibernateDaoSupport {

public Collection getEmpByDept(String dept) throws DataAccessException, MyException {public Collection getEmpByDept(String dept) throws DataAccessException, MyException {Session session = getSession(false);Session session = getSession(false);try {try {Query query = session.createQuery("from com.bean.Emp e where e.dept=?");Query query = session.createQuery("from com.bean.Emp e where e.dept=?");query.setString(0, dept);query.setString(0, dept);List result = query.list();List result = query.list();if (result == null) {if (result == null) {throw new MyException("No results.");throw new MyException("No results.");}}return result;return result;}}catch (HibernateException ex) {catch (HibernateException ex) {throw convertHibernateAccessException(ex);throw convertHibernateAccessException(ex);}}}}}}

Page 23: Spring

InheritenceInheritence

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

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

    <bean id="parent"     <bean id="parent" classclass="mybean" >="mybean" >        <property name="name" value="Roseindia.net"/>        <property name="name" value="Roseindia.net"/>    </bean>    </bean>

    <bean id="child"     <bean id="child" classclass="mybean" parent="parent">="mybean" parent="parent">        <property name="address" value="Rohini"/>        <property name="address" value="Rohini"/>    </bean>    </bean>

    <bean id="subchild"     <bean id="subchild" classclass="mybean" parent="parent"/>="mybean" parent="parent"/>

</beans></beans>

Page 24: Spring

import import org.springframework.beans.factory.xml.XmlBeanFactory;org.springframework.beans.factory.xml.XmlBeanFactory;import import org.springframework.core.io.ClassPathResource;org.springframework.core.io.ClassPathResource;

public class public class Main {Main {

    public static void public static void main(String[] args) main(String[] args) throws throws Exception {Exception {    XmlBeanFactory bf =     XmlBeanFactory bf = new new XmlBeanFactory(XmlBeanFactory(new new ClassPathResource("context.xml"));ClassPathResource("context.xml"));    System.out.println("===============Inheritance demo=================");    System.out.println("===============Inheritance demo=================");    System.out.println(bf.getBean("child"));    System.out.println(bf.getBean("child"));    System.out.println(bf.getBean("subchild"));    System.out.println(bf.getBean("subchild"));          }  }}}class class mybean {mybean {    private private String name;String name;    private private String address;String address;

    public void public void setName(String name) {setName(String name) {            thisthis.name = name;.name = name;  }  }

        public void public void setAddress(String address) {setAddress(String address) {                thisthis.address = address;.address = address;    }    }    @Override  @Override    public public String toString() {String toString() {            final final StringBuilder stringBuilder = StringBuilder stringBuilder = new new StringBuilder();StringBuilder();      stringBuilder.append("Bean");      stringBuilder.append("Bean");      stringBuilder.append("{name='").append(name).append('\'');      stringBuilder.append("{name='").append(name).append('\'');      stringBuilder.append(", address=").append(address);      stringBuilder.append(", address=").append(address);                stringBuilder.append('}');      stringBuilder.append('}');            return return stringBuilder.toString();stringBuilder.toString();  }  }} }

Output:Output:Nov 25, 2008 3:39:29 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReadeNov 25, 2008 3:39:29 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [context.xml] r loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [context.xml] ===============Inheritance demo================= ===============Inheritance demo================= Bean{name='Roseindia.net', address=Rohini} Bean{name='Roseindia.net', address=Rohini} Bean{name='Roseindia.net', address=null} Bean{name='Roseindia.net', address=null} BUILD SUCCESSFUL (total time: 1 second) BUILD SUCCESSFUL (total time: 1 second)

Page 25: Spring

Property injectionProperty injection

<?xml version="1.0" encoding="UTF-8"?><?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"<beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:p="http://www.springframework.org/schema/p"       xmlns:p="http://www.springframework.org/schema/p"       xsi:schemaLocation="       xsi:schemaLocation="       http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans.xsd">       http://www.springframework.org/schema/beans/spring-beans.xsd">    <bean id="mybean"     <bean id="mybean"                     classclass="Inject"="Inject"          p:name="Girish"           p:name="Girish"           p:age="24"           p:age="24"           p:address="Noida"           p:address="Noida"           p:company="Roseindia.net"           p:company="Roseindia.net"           p:email="[email protected]"/>          p:email="[email protected]"/></beans> </beans>

Page 26: Spring

import import org.springframework.beans.factory.xml.XmlBeanFactory;org.springframework.beans.factory.xml.XmlBeanFactory;import import org.springframework.core.io.ClassPathResource;org.springframework.core.io.ClassPathResource;

public class public class Main {Main {

        public static void public static void main(String[] args) {main(String[] args) {        XmlBeanFactory beanFactory =         XmlBeanFactory beanFactory = new new XmlBeanFactory(XmlBeanFactory(new new ClassPathResource(ClassPathResource(                "context.xml"));                "context.xml"));        Inject demo = (Inject) beanFactory.getBean("mybean");        Inject demo = (Inject) beanFactory.getBean("mybean");        System.out.println(demo);        System.out.println(demo);    }    }}}

class class Inject {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) {                thisthis.address = address;.address = address;    }    }

        public void public void setCompany(String company) {setCompany(String company) {                thisthis.company = company;.company = company;    }    }

        public void public void setEmail(String email) {setEmail(String email) {                thisthis.email = email;.email = email;    }    }

        public void public void setAge(setAge(int int age) {age) {                thisthis.age = age;.age = age;    }    }

        public void public void setName(String name) {setName(String name) {                thisthis.name = name;.name = name;    }    }

    @Override    @Override        public public String toString() {String toString() {                return return String.format("Name: %s\n" +String.format("Name: %s\n" +                "Age: %d\n" +                "Age: %d\n" +                "Address: %s\n" +                "Address: %s\n" +                "Company: %s\n" +                "Company: %s\n" +                "E-mail: %s",                "E-mail: %s",                                thisthis.name, .name, thisthis.age, .age, thisthis.address, .address, thisthis.company, .company, thisthis.email);.email);    }    }} }

Page 27: Spring

This controller is use to redirect the page in the Spring 2.5 Web MVC applications. This controller doesn't  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 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 as a JSP. we will configure just declared the ParameterizableViewControllerParameterizableViewController bean and set the view name bean and set the view name through the "through the "viewNameviewName" property." property.

Now we will used ParameterizedViewController  for control the behavior of the application.Now we will used ParameterizedViewController  for control the behavior of the application.

Example:Example:

1) index.jsp1) index.jsp

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

<a href=<a href="parameterizableviewcontroller.html""parameterizableviewcontroller.html">ParameterizableViewController Example</a>>ParameterizableViewController Example</a>

Page 28: Spring

<?xml version=<?xml version="1.0""1.0" encoding= encoding="UTF-8""UTF-8"?>?><beans xmlns=<beans xmlns="http://www.springframework.org/schema/beans""http://www.springframework.org/schema/beans"

xmlns:xsi=xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance""http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=xsi:schemaLocation="http://www.springframework.org/schema/beans "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">><bean class=<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping""org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">>

<property name=<property name="mappings""mappings">><props><props> <prop key=<prop key="/parameterizableviewcontroller.html""/parameterizableviewcontroller.html">parameterizableController</prop>>parameterizableController</prop></props></props>

</property></property></bean> </bean>

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

</bean> </bean>

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

<value>/WEB-INF/jsp/</value><value>/WEB-INF/jsp/</value></property></property><property name=<property name="suffix""suffix">>

<value>.jsp</value><value>.jsp</value></property></property>

</bean> </bean> </beans></beans>

Page 29: Spring

UMLFilenameViewControllerUMLFilenameViewController If user don't want to include any logical operation on request and redirect to some resource then user used  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 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. user interface. In this example we will discuss about UrlFileNameViewController.

<?xml version=<?xml version="1.0""1.0" encoding= encoding="UTF-8""UTF-8"?>?><beans xmlns=<beans xmlns="http://www.springframework.org/schema/beans""http://www.springframework.org/schema/beans"

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

<bean id=<bean id=""staticViewControllerstaticViewController"" class= class="org.springframework.web.servlet.mvc."org.springframework.web.servlet.mvc.UrlFilenameViewControllerUrlFilenameViewController""/> />

<bean id=<bean id="urlMapping“ "urlMapping“ class=class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping""org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">><property name=<property name="interceptors""interceptors">>

<list><list> <ref local=<ref local="localeChangeInterceptor""localeChangeInterceptor"/>/></list></list>

</property></property><property name=<property name="urlMap""urlMap">>

<map> <map> <entry key=<entry key="/*.html""/*.html">> <ref bean=<ref bean=""staticViewControllerstaticViewController""/>/> </entry></entry></map> </map>

</property> </property> </bean></bean>

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

<value>/WEB-INF/</value><value>/WEB-INF/</value></property></property><property name=<property name="suffix""suffix">>

<value>.<value>.jspjsp</value></value></property></property>

</bean></bean>

Page 30: Spring

Index.jspIndex.jsp<html><html><head></head><head></head><body><body><h3>UrlFileNameViewController Example</h3><h3>UrlFileNameViewController Example</h3><h4><a href=<h4><a href="MyAddress.html""MyAddress.html">My Home Address</a></h4><br/>>My Home Address</a></h4><br/><h4><a href=<h4><a href="MyOfficeAddress.html""MyOfficeAddress.html">My Office Address</a></h4>>My Office Address</a></h4></body></body></html></html>

Page 31: Spring

AbstractWizardFormControllerAbstractWizardFormController Spring Web MVC provides Spring Web MVC provides AbstractWizardFormController AbstractWizardFormController class that handle wizard form. In this tutorial, we will used class that handle wizard form. In this tutorial, we will used

AbstractWizardFormController AbstractWizardFormController class. The AbstractWizardFormController class provide us to store and show the forms 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 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.whole model object at once. In this tutorial we will discuss about this controller.

index.jspindex.jsp

<%@page contentType=<%@page contentType="text/html""text/html" pageEncoding= pageEncoding="UTF-8""UTF-8"%>%><html><head><html><head><title>AbstractWizardFormController Example</title><title>AbstractWizardFormController Example</title></head><body></head><body><center><center><a href=<a href="user1.html""user1.html">>AbstractWizardFormController Test Application</a><br/> AbstractWizardFormController Test Application</a><br/> </center></body></html></center></body></html>

Page 32: Spring

<?xml version=<?xml version="1.0""1.0" encoding= encoding="UTF-8""UTF-8"?>?><beans xmlns=<beans xmlns=""http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans""

xmlns:xsi=xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instancehttp://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=xsi:schemaLocation="http://www.springframework.org/schema/beans "http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd"" xmlns:p= xmlns:p="http://www.springframework.org/schema/p""http://www.springframework.org/schema/p"> >

<bean id=<bean id="urlMapping“ "urlMapping“ class=class=""org.springframework.web.servlet.handler.SimpleUrlHandlerMappingorg.springframework.web.servlet.handler.SimpleUrlHandlerMapping"">><property name=<property name="interceptors""interceptors">><list> <ref local=<list> <ref local="localeChangeInterceptor""localeChangeInterceptor"/> </list>/> </list></property></property><property name=<property name="urlMap""urlMap">>

<map> <map> <entry key= <entry key=""/user1.html/user1.html"">>

<ref bean= <ref bean=""wizardControllerwizardController""/></entry> /></entry> </map> </map> </property></bean> </property></bean>

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

<bean id=<bean id="localeChangeInterceptor""localeChangeInterceptor" class= class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor""org.springframework.web.servlet.i18n.LocaleChangeInterceptor">> <property name= <property name="paramName""paramName" value= value="hl""hl"/>/> </bean> </bean>

<bean id=<bean id="localeResolver""localeResolver" class= class="org.springframework.web.servlet.i18n.SessionLocaleResolver""org.springframework.web.servlet.i18n.SessionLocaleResolver" /> /> <bean id=<bean id="viewResolver“ c"viewResolver“ class=lass="org.springframework.web.servlet.view.InternalResourceViewResolver""org.springframework.web.servlet.view.InternalResourceViewResolver">>

<property name=<property name="prefix""prefix">><value>/WEB-INF/<value>/WEB-INF/jspjsp/</value>/</value></property></property><property name=<property name="suffix""suffix">><value>.<value>.jspjsp</value></value></property></property></bean></bean>

</beans></beans>

Page 33: Spring

User1.jspUser1.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>First 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%"> <center><table><tr><td align="right" width="20%"> <strong>First Name:</strong></td><td style="width: 20%"><strong>First Name:</strong></td><td style="width: 20%"><spring:bind path="user.firstName"><spring:bind path="user.firstName"><input type="text" name="firstName" value="<c:out value="${status.value}"/>"/><input type="text" name="firstName" value="<c:out value="${status.value}"/>"/></spring:bind></td><td><font color="red"></spring:bind></td><td><font color="red"><form:errors path="firstName"/></font></td></tr><tr><td align="right" <form:errors path="firstName"/></font></td></tr><tr><td align="right"

width="20%"> width="20%"> <strong>Last Name:</strong></td><td style="width: 20%"><strong>Last Name:</strong></td><td style="width: 20%"><spring:bind path="user.lastName"><spring:bind path="user.lastName"><input type="text" name="lastName" value="<c:out value="${status.value}"/>"/><input type="text" name="lastName" value="<c:out value="${status.value}"/>"/></spring:bind></td><td><font color="red"></spring:bind></td><td><font color="red"><form:errors path="lastName"/></font></td></tr><tr><form:errors path="lastName"/></font></td></tr><tr><td align="right" width="20%"> <td align="right" width="20%"> <strong>Email Id:</strong></td><td style="width: 40%"><strong>Email Id:</strong></td><td style="width: 40%"><spring:bind path="user.emailId"><spring:bind path="user.emailId"><input type="text" name="emailId" value="<c:out value="${status.value}"/>"/><input type="text" name="emailId" value="<c:out value="${status.value}"/>"/></spring:bind></td><td><font color="red"></spring:bind></td><td><font color="red"><form:errors path="emailId"/></font></td></tr><tr><td align="right" <form:errors path="emailId"/></font></td></tr><tr><td align="right"

width="20%">width="20%"><strong>Contact:</strong></td><td style="width: 40%"><strong>Contact:</strong></td><td style="width: 40%"><spring:bind path="user.contact"><spring:bind path="user.contact"><input type="text" name="contact" value="<c:out value="${status.value}"/>"/><input type="text" name="contact" value="<c:out value="${status.value}"/>"/></spring:bind></td><td><font color="red"></spring:bind></td><td><font color="red"><form:errors path="contact"/></font></td></tr><tr><td align="right" width="20%"><form:errors path="contact"/></font></td></tr><tr><td align="right" width="20%"> <strong>Gender:</strong></td><td style="width: 40%"><strong>Gender:</strong></td><td style="width: 40%"><spring:bind path="user.gender"><spring:bind path="user.gender"><input type="text" name="gender" 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="gender"/></font></td></tr><tr><td ><strong></strong></td><td colspan="2"><td colspan="2"><input type="submit" name="_cancel" value="Cancle"/><input type="submit" name="_cancel" value="Cancle"/><input type="submit" name="_target1" value="Next"/><input type="submit" name="_target1" value="Next"/><input type="submit" name="_target2" value="Finish"/></td></tr><input type="submit" name="_target2" value="Finish"/></td></tr></table></center></form:form></table></center></form:form></body></html></body></html>

User2.jspUser2.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>Second 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%"> <center><table><tr><td align="right" width="20%">

<strong>Date of birth:</strong></td><td style="width: 50%"><strong>Date of birth:</strong></td><td style="width: 50%">

<spring:bind path="user.dob"><spring:bind path="user.dob">

<input type="text" name="dob" value="<c:out value="${status.value}"/>"/><input type="text" name="dob" value="<c:out value="${status.value}"/>"/>

</spring:bind></td><td><font color="red"></spring:bind></td><td><font color="red">

<form:errors path="dob"/></font></td></tr><tr><td align="right" width="20%"> <form:errors path="dob"/></font></td></tr><tr><td align="right" width="20%">

<strong>Address:</strong></td><td style="width: 50%"><strong>Address:</strong></td><td style="width: 50%">

<spring:bind path="user.address"><spring:bind path="user.address">

<input type="text" name="address" value="<c:out value="${status.value}"/>"/><input type="text" name="address" value="<c:out value="${status.value}"/>"/>

</spring:bind></td><td></spring:bind></td><td>

<font color="red"><form:errors path="address"/></font></td></tr><tr><td align="right" <font color="red"><form:errors path="address"/></font></td></tr><tr><td align="right" width="20%">width="20%">

<strong>Country:</strong></td><td style="width: 50%"><strong>Country:</strong></td><td style="width: 50%">

<spring:bind path="user.country"><spring:bind path="user.country">

<input type="text" name="country" value="<c:out value="${status.value}"/>"/><input type="text" name="country" value="<c:out value="${status.value}"/>"/>

</spring:bind></td><td><font color="red"></spring:bind></td><td><font color="red">

<form:errors path="country"/></font></td></tr><tr><td align="right" width="20%"> <form:errors path="country"/></font></td></tr><tr><td align="right" width="20%">

<strong>Qualification:</strong></td><td style="width: 50%"><strong>Qualification:</strong></td><td style="width: 50%">

<spring:bind path="user.qualification"><spring:bind path="user.qualification">

<input type="text" name="qualification" value="<c:out value="${status.value}"/>"/><input type="text" name="qualification" value="<c:out value="${status.value}"/>"/>

</spring:bind></td><td><font color="red"></spring:bind></td><td><font color="red">

<form:errors path="qualification"/></font></td></tr><tr><td ></td><td style="width: 50%" <form:errors path="qualification"/></font></td></tr><tr><td ></td><td style="width: 50%" >>

<input type="submit" name="_target0" value="Previous"/><input type="submit" name="_target0" value="Previous"/>

<input type="submit" name="_target2" value="Next"/><input type="submit" name="_target2" value="Next"/>

<input type="submit" name="_cancel" value="Cancle"/><input type="submit" name="_cancel" value="Cancle"/>

<input type="submit" name="_target2" value="Finish"/></td></tr></table><input type="submit" name="_target2" value="Finish"/></td></tr></table>

</center></form:form></body></html></center></form:form></body></html>

Page 34: Spring

User3.jspUser3.jsp<%@ page language="java" contentType="text/html; <%@ page language="java" contentType="text/html;

charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><%@ taglib prefix="form" <%@ taglib prefix="form"

uri="http://www.springframework.org/tags/form"%>uri="http://www.springframework.org/tags/form"%><%@ taglib prefix="spring" <%@ taglib prefix="spring"

uri="http://www.springframework.org/tags"%>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>Show Details</title></head><html><head><title>Show Details</title></head><body><body><form:form method="POST" commandName="user"><form:form method="POST" commandName="user"><center><table><tr><td style="width: 56%" colspan="2"><center><table><tr><td style="width: 56%" colspan="2"><strong>The Values entered are as <strong>The Values entered are as

follow</strong></td></tr><tr><td align="right" follow</strong></td></tr><tr><td align="right" width="20%"> width="20%">

<strong>First Name:</strong></td><td style="width: 56%"><strong>First Name:</strong></td><td style="width: 56%">${user.firstName}</td></tr><tr><td align="right" ${user.firstName}</td></tr><tr><td align="right"

width="20%"> width="20%"> <strong>Last Name:</strong></td><td style="width: 56%"><strong>Last Name:</strong></td><td style="width: 56%">${user.lastName}</td></tr><tr><td align="right" ${user.lastName}</td></tr><tr><td align="right"

width="20%"> width="20%"> <strong>Email Id:</strong></td><td style="width: 56%"><strong>Email Id:</strong></td><td style="width: 56%">${user.emailId}</td></tr><tr><td align="right" width="20%"> ${user.emailId}</td></tr><tr><td align="right" width="20%"> <strong>Contact:</strong></td><td style="width: 56%"><strong>Contact:</strong></td><td style="width: 56%">${user.contact}</td></tr><tr><td align="right" width="20%"> ${user.contact}</td></tr><tr><td align="right" width="20%"> <strong>Gender:</strong></td><td style="width: 56%"><strong>Gender:</strong></td><td style="width: 56%">${user.gender}</td></tr><tr><td align="right" width="20%"> ${user.gender}</td></tr><tr><td align="right" width="20%"> <strong>Date of Birth:</strong></td><td style="width: 56%"><strong>Date of Birth:</strong></td><td style="width: 56%">${user.dob}</td></tr><tr><td align="right" width="20%">${user.dob}</td></tr><tr><td align="right" width="20%"><strong>Address:</strong></td><td style="width: 56%"><strong>Address:</strong></td><td style="width: 56%">${user.address}</td></tr><tr><td align="right" width="20%"> ${user.address}</td></tr><tr><td align="right" width="20%"> <strong>Country:</strong></td><td style="width: 56%"><strong>Country:</strong></td><td style="width: 56%">${user.country}</td></tr><tr><td align="right" width="20%"> ${user.country}</td></tr><tr><td align="right" width="20%"> <strong>Qualification:</strong></td><td style="width: 56%"><strong>Qualification:</strong></td><td style="width: 56%">${user.qualification}</td></tr></table></center>${user.qualification}</td></tr></table></center></form:form></body></html></form:form></body></html>

public class public class User {User {        private private String firstName;String firstName;    private private String lastName;String lastName;    private private String emailId;String emailId;    private private String contact;    String contact;        private private String gender;String gender;        private private String dob;String dob;    private private String address;String address;    private private String country;String country;    private private String qualification;String qualification;            public void public void setFirstName(String firstName){setFirstName(String firstName){        thisthis.firstName = firstName;.firstName = firstName;  }  }    public public String getFirstName(){String getFirstName(){        return return firstName;firstName;  }  }    public void public void setLastName(String lastName){setLastName(String lastName){        thisthis.lastName = lastName;.lastName = lastName;  }  }    public public String getLastName(){String getLastName(){        return return lastName;lastName;  }  }    public void public void setEmailId(String emailId){setEmailId(String emailId){        thisthis.emailId = emailId;.emailId = emailId;  }  }    public public String getEmailId(){String getEmailId(){        return return emailId;emailId;  }  }    public void public void setContact(String contact){setContact(String contact){        thisthis.contact = contact;.contact = contact;  }  }    public public String getContact(){String getContact(){        return return contact;contact;  }  }    public void public void setAddress(String address){setAddress(String address){        thisthis.address = address;.address = address;  }  }    public public String getAddress(){String getAddress(){        return return address;address;  }  }    public void public void setGender(String gender){setGender(String gender){        thisthis.gender = gender;.gender = gender;  }  }    public public String getGender(){String getGender(){        return return gender;gender;  }  }    public void public void setDob(String dob){setDob(String dob){        thisthis.dob = dob;.dob = dob;  }  }    public public String getDob(){String getDob(){        return return dob;dob;  }  }    public void public void setCountry(String country){setCountry(String country){        thisthis.country = country;.country = country;  }  }    public public String getCountry(){String getCountry(){        return return country;country;  }  }    public void public void setQualification(String qualification){setQualification(String qualification){        thisthis.qualification = qualification;.qualification = qualification;  }  }    public public String getQualification(){String getQualification(){        return return qualification;qualification;  }  }} }

Page 35: Spring

importimport java.util.regex.Matcher; java.util.regex.Matcher;importimport java.util.regex.Pattern; java.util.regex.Pattern;

importimport javax.servletjavax.servlet.http.HttpServletRequest;.http.HttpServletRequest;importimport javax.servletjavax.servlet.http.HttpServletResponse;.http.HttpServletResponse;importimport org.springframeworkorg.springframework.validation.BindException;.validation.BindException;importimport org.springframeworkorg.springframework.validation.Errors;.validation.Errors;importimport org.springframeworkorg.springframework.web.servlet.ModelAndView;.web.servlet.ModelAndView;importimport org.springframeworkorg.springframework.web.servlet.mvc.AbstractWizardFormController;.web.servlet.mvc.AbstractWizardFormController;importimport org.springframeworkorg.springframework.web.servlet.view.RedirectView;.web.servlet.view.RedirectView;importimport netnet.roseindia.web.User;.roseindia.web.User;

publicpublic classclass AWizardFormControllerAWizardFormController extendsextends AbstractWizardFormControllerAbstractWizardFormController { { @Override@Override protectedprotected ModelAndViewModelAndView processCancel( processCancel(HttpServletRequestHttpServletRequest request, request, HttpServletResponseHttpServletResponse response, Object command, response, Object command, BindExceptionBindException errors) errors) throwsthrows Exception { Exception { // Logical code// Logical code System.System.outout.println("processCancel");.println("processCancel"); returnreturn newnew ModelAndViewModelAndView((newnew RedirectViewRedirectView("user1.html"));("user1.html")); }}

@Override@Override protectedprotected ModelAndViewModelAndView processFinish( processFinish(HttpServletRequestHttpServletRequest request, request, HttpServletResponseHttpServletResponse response, Object command, response, Object command, BindExceptionBindException errors) errors) throwsthrows Exception { Exception { // Logical code// Logical code System.System.outout.println("processFinish");.println("processFinish"); returnreturn newnew ModelAndViewModelAndView((newnew RedirectViewRedirectView("user4.html"));("user4.html"));

}}

protectedprotected voidvoid validatePage(Object command, validatePage(Object command, ErrorsErrors errors, errors, intint page) { page) { UserUser user = ( user = (UserUser) command;) command;

ifif (page == 0) { (page == 0) { ifif (user.getFirstName() == "") { (user.getFirstName() == "") { errors.rejectValue("firstName", "error.too-high", errors.rejectValue("firstName", "error.too-high", nullnull,, "First Name cannot be empty.");"First Name cannot be empty."); }} ifif (user.getLastName() == "") { (user.getLastName() == "") { errors.rejectValue("lastName", "error.too-high", errors.rejectValue("lastName", "error.too-high", nullnull,, "Last Name cannot be empty.");"Last Name cannot be empty."); }} ifif (user.getEmailId() == "") { (user.getEmailId() == "") { errors.rejectValue("emailId", "error.too-high", errors.rejectValue("emailId", "error.too-high", nullnull,, "EmailId cannot be empty.");"EmailId cannot be empty."); }} ifif ((user.getEmailId() != "") || (user.getEmailId().length()) != 0) { ((user.getEmailId() != "") || (user.getEmailId().length()) != 0) { Pattern p = Pattern.Pattern p = Pattern.compilecompile(".+@.+\\.[a-z]+");(".+@.+\\.[a-z]+"); Matcher m = p.matcher(user.getEmailId());Matcher m = p.matcher(user.getEmailId()); booleanboolean b = m.matches(); b = m.matches();

ifif (b != (b != truetrue) {) {

errors.rejectValue("emailId", "error.is.not.valid",errors.rejectValue("emailId", "error.is.not.valid",

"Email ID does not Valid ");"Email ID does not Valid ");

}}

}}

ifif (user.getContact() == "") { (user.getContact() == "") {

errors.rejectValue("contact", "error.too-high", errors.rejectValue("contact", "error.too-high", nullnull,,

"Contact cannot be empty.");"Contact cannot be empty.");

}}

ifif ((user.getContact() != "") || (user.getContact().length()) != 0) { ((user.getContact() != "") || (user.getContact().length()) != 0) {

Pattern pattern = Pattern.Pattern pattern = Pattern.compilecompile("\\d{1}-\\d{4}-\\d{6}");("\\d{1}-\\d{4}-\\d{6}");

Matcher matcher = pattern.matcher(user.getContact());Matcher matcher = pattern.matcher(user.getContact());

booleanboolean con = matcher.matches(); con = matcher.matches();

ifif (con != (con != truetrue) {) {

errors.rejectValue("contact", "error.is.not.valid",errors.rejectValue("contact", "error.is.not.valid",

"Enter Contact Number Like 0-9999-999999");"Enter Contact Number Like 0-9999-999999");

}}

}}

ifif (user.getGender() == "") { (user.getGender() == "") {

errors.rejectValue("gender", "error.too-high", errors.rejectValue("gender", "error.too-high", nullnull,,

"Gender cannot be empty.");"Gender cannot be empty.");

}}

}}

ifif (page == 1) { (page == 1) {

ifif (user.getDob() == "") { (user.getDob() == "") {

errors.rejectValue("dob", "error.too-high", errors.rejectValue("dob", "error.too-high", nullnull,,

"Date of birth cannot be empty.");"Date of birth cannot be empty.");

}}

ifif ((user.getDob() != "") || (user.getDob().length()) != 0) { ((user.getDob() != "") || (user.getDob().length()) != 0) {

Pattern pattern = Pattern.Pattern pattern = Pattern.compilecompile("\\d{2}/\\d{2}/\\d{4}");("\\d{2}/\\d{2}/\\d{4}");

Matcher matcher = pattern.matcher(user.getDob());Matcher matcher = pattern.matcher(user.getDob());

booleanboolean DOB = matcher.matches(); DOB = matcher.matches();

ifif (DOB != (DOB != truetrue) {) {

errors.rejectValue("dob", "error.is.not.valid",errors.rejectValue("dob", "error.is.not.valid",

"Enter Date of birth Like 01/02/1986 ");"Enter Date of birth Like 01/02/1986 ");

}}

}}

ifif (user.getAddress() == "") { (user.getAddress() == "") {

errors.rejectValue("address", "error.too-high", errors.rejectValue("address", "error.too-high", nullnull,,

"Address cannot be empty.");"Address cannot be empty.");

}}

ifif (user.getCountry() == "") { (user.getCountry() == "") {

errors.rejectValue("country", "error.too-high", errors.rejectValue("country", "error.too-high", nullnull,,

"Country cannot be empty.");"Country cannot be empty.");

}}

ifif (user.getQualification() == "") { (user.getQualification() == "") {

errors.rejectValue("qualification", "error.too-high", errors.rejectValue("qualification", "error.too-high", nullnull,,

"Qualification cannot be empty.");"Qualification cannot be empty.");

}}

}}

}}

}}

Page 36: Spring

SimpleFromControllerSimpleFromControllerSpring provides SimpleFromController for control a form data in the web application. If you want to handle form in spring then 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 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 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 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 displayexample we will create a form that accept user data and display

Index.jspIndex.jsp <%@page contentType=<%@page contentType="text/html""text/html" pageEncoding= pageEncoding="UTF-8""UTF-8"%>%>

<html><head><title>User Welcome Page</title></head> <html><head><title>User Welcome Page</title></head> <body bgcolor=<body bgcolor="#EEEEEE""#EEEEEE">><center><center><a href=<a href="user.html""user.html">Fill User Personal Details</a>>Fill User Personal Details</a></center></body></html> </center></body></html>

Page 37: Spring

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

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

<bean id=<bean id="urlMapping""urlMapping"

class=class="org.springframework.web.servlet.handler.SimpleUrlHandlerM"org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"apping">>

<property name=<property name="interceptors""interceptors">> <list><list> <ref local=<ref local="localeChangeInterceptor""localeChangeInterceptor" /> /> </list></list> </property></property> <property name=<property name="urlMap""urlMap">> <map><map> <entry key=<entry key="/user.html""/user.html">> <ref bean=<ref bean="userController""userController" /> /> </entry></entry> </map></map> </property></property> </bean></bean>

<bean id=<bean id="userValidator""userValidator" class= class="net.roseindia.web.UserValidator""net.roseindia.web.UserValidator" /> />

<bean id=<bean id="userController""userController" class= class="net.roseindia.web.UserFormController""net.roseindia.web.UserFormController">>

<property name=<property name="sessionForm""sessionForm">>

<value>false</value><value>false</value>

</property></property>

<property name=<property name="commandName""commandName">>

<value>user</value><value>user</value>

</property></property>

<property name=<property name="commandClass""commandClass">>

<value>net.roseindia.web.User</value><value>net.roseindia.web.User</value>

</property></property>

<property name=<property name="validator""validator">>

<ref bean=<ref bean="userValidator""userValidator" /> />

</property></property>

<property name=<property name="formView""formView">>

<value>user</value><value>user</value>

</property></property>

<property name=<property name="successView""successView">>

<value>usersuccess</value><value>usersuccess</value>

</property></property>

</bean></bean>

<bean id=<bean id="localeChangeInterceptor""localeChangeInterceptor"

class=class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor""org.springframework.web.servlet.i18n.LocaleChangeInterceptor">>

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

</bean></bean>

<bean id=<bean id="localeResolver""localeResolver"

class=class="org.springframework.web.servlet.i18n.SessionLocaleResolver""org.springframework.web.servlet.i18n.SessionLocaleResolver" /> />

</beans></beans>

Page 38: Spring

User.jspUser.jsp<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %><%@ taglib prefix="spring" uri="/spring"%><%@ taglib prefix="spring" uri="/spring"%><%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"

%>%><html><html> <head><head> <title>User Personal Details</title><title>User Personal Details</title> </head></head> <body><body> <center><center> <h3>User Personal Details</h3><h3>User Personal Details</h3> <br /><br /> <form:form commandName=<form:form commandName="user""user" method= method="POST""POST" name= name="user""user">> <table border=<table border="0""0">> <tr><tr> <td>Name:</td><td>Name:</td> <td><td> <form:input path=<form:input path="name""name" /> /> </td></td> <td><td> <font color=<font color="red""red">> <form:errors path=<form:errors path="name""name" /> /> </font></font> </td></td> </tr></tr> <tr><tr> <td>Email ID:</td><td>Email ID:</td> <td><td> <form:input path=<form:input path="emailid""emailid" /> /> </td></td> <td><td> <font color=<font color="red""red">> <form:errors path=<form:errors path="emailid""emailid" /> /> </font></font> </td></td> </tr></tr>

<tr><tr>

<td>Date of birth:</td><td>Date of birth:</td>

<td><td>

<form:input path=<form:input path="dob""dob" /> />

</td></td>

<td><td>

<font color=<font color="red""red">>

<form:errors path=<form:errors path="dob""dob" /> />

</font></font>

</td></td>

</tr></tr>

<tr><tr>

<td>Qualification:</td><td>Qualification:</td>

<td><td>

<form:input path=<form:input path="qualification""qualification" /> />

</td></td>

<td><td>

<font color=<font color="red""red">>

<form:errors path=<form:errors path="qualification""qualification" /> />

</font></font>

</td></td>

</tr></tr>

<tr><tr>

<td>Contact Number:</td><td>Contact Number:</td>

<td><td>

<form:input path=<form:input path="contact""contact" /> />

</td></td>

<td><td>

<font color=<font color="red""red">>

<form:errors path=<form:errors path="contact""contact" /> />

</font></font>

</td></td>

</tr></tr>

<tr><tr>

<td>Address:</td><td>Address:</td>

<td><td>

<form:input path=<form:input path="address""address" /> />

</td></td>

<td><td>

<font color=<font color="red""red">>

<form:errors path=<form:errors path="address""address" /> />

</font></font>

</td></td>

</tr></tr>

<tr><tr>

<td colspan=<td colspan="3""3" align= align="center""center">>

<input type=<input type="submit""submit" value= value="Save""Save" /> />

</td></td>

</tr></tr>

</table></table>

</form:form></form:form>

</center></center>

</body></body>

</html></html>

Page 39: Spring

userSuccess.jspuserSuccess.jsp<%@ page session="false"%><%@ page session="false"%><%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %><%@ taglib prefix="spring" uri="/spring" %><%@ taglib prefix="spring" uri="/spring" %><html><html> <head><head> <title>User Personal Details Display</title><title>User Personal Details Display</title> </head></head> <body><body> <center><center> <h3>User Personal Details Display</h3><h3>User Personal Details Display</h3> <br><br> <table><table> <tr><tr> <td colspan=<td colspan="2""2" align= align="center""center">> <font size=<font size="5""5">User Information</font>>User Information</font> </td></td> </tr></tr> <tr><tr> <td>Name:</td><td>Name:</td> <td><td> <core:out value=<core:out value="${user.name}""${user.name}" /> /> </td></td> </tr></tr> <tr><tr> <td>Email ID:</td><td>Email ID:</td> <td><td> <core:out value=<core:out value="${user.emailid}""${user.emailid}" /> /> </td></td> </tr></tr> <tr><tr> <td>Date Of Birth:</td><td>Date Of Birth:</td> <td><td> <core:out value=<core:out value="${user.dob}""${user.dob}" /> /> </td></td> </tr></tr>

<tr><tr>

<td>Qualification:</td><td>Qualification:</td>

<td><td>

<core:out value=<core:out value="${user.qualification}""${user.qualification}" /> />

</td></td>

</tr></tr>

<tr><tr>

<td>Contact Number:</td><td>Contact Number:</td>

<td><td>

<core:out value=<core:out value="${user.contact}""${user.contact}" /> />

</td></td>

</tr></tr>

<tr><tr>

<td>Address:</td><td>Address:</td>

<td><td>

<core:out value=<core:out value="${user.address}""${user.address}" /> />

</td></td>

</tr></tr>

</table></table>

<a href=<a href="user.html""user.html">Back</a>>Back</a>

</center></center>

</body></body>

</html></html>

Page 40: Spring

public class public class User {User {      public public User(){}User(){}          private private String name;    String name;            private private String emailid;String emailid;        private private String dob;String dob;        private private String address;String address;        private private String qualification;String qualification;        private private String contact;String contact;

        public public String getDob() {String getDob() {                return return dob;dob;    }    }        public void public void setDob(String dob) {setDob(String dob) {                thisthis.dob = dob;.dob = dob;    }    }        public public String getQualification() {String getQualification() {                return return qualification;qualification;    }    }

        public void public void setQualification(String qualification) {setQualification(String qualification) {                thisthis.qualification = qualification;.qualification = qualification;    }    }        public public String getContact() {String getContact() {                return return contact;contact;    }    }

        public void public void setContact(String contact) {setContact(String contact) {                thisthis.contact = contact;.contact = contact;    }    }

        public public String getName() {String getName() {                return return name;name;    }    }

        public void public void setName(String name) {setName(String name) {                thisthis.name = name;.name = name;

    }    }        public public String getEmailid() {String getEmailid() {                return return emailid;emailid;    }    }

        public void public void setEmailid(String emailid) {setEmailid(String emailid) {                thisthis.emailid = emailid;.emailid = emailid;    }    }        public public String getAddress() {String getAddress() {                return return address;address;    }    }

        public void public void setAddress(String address) {setAddress(String address) {                thisthis.address = address;.address = address;    }    }} }

package package net.roseindia.web;net.roseindia.web;

import import javax.servlet.http.HttpServletRequest;javax.servlet.http.HttpServletRequest;import import javax.servlet.ServletException;javax.servlet.ServletException;import import org.springframework.web.servlet.ModelAndView;org.springframework.web.servlet.ModelAndView;import import org.springframework.web.servlet.view.RedirectViorg.springframework.web.servlet.view.RedirectView;ew;import import org.springframework.web.servlet.mvc.SimpleFororg.springframework.web.servlet.mvc.SimpleFormController;mController;

import import net.roseindia.web.User;net.roseindia.web.User;

@SuppressWarnings("deprecation")@SuppressWarnings("deprecation")public class public class UserFormControllerUserFormController  extends extends SimpleFormCoSimpleFormControllerntroller { {      @Override  @Override    protected protected ModelAndView onSubmit(Object command) ModelAndView onSubmit(Object command) tthrows hrows ServletException {ServletException {    User user = (User) command;        User user = (User) command;                ModelAndView modelAndView =     ModelAndView modelAndView = new new ModelAndVieModelAndView(getSuccessView());w(getSuccessView());    modelAndView.addObject("user", user);    modelAndView.addObject("user", user);        return return modelAndView;    modelAndView;        }    }} }

Page 41: Spring

packagepackage net.roseindia.webnet.roseindia.web;;

importimport java.util.regex.*; java.util.regex.*;importimport org.springframeworkorg.springframework.validation.Errors;.validation.Errors;importimport org.springframeworkorg.springframework.validation.Validator;.validation.Validator;importimport netnet.roseindia.web.User;.roseindia.web.User;

publicpublic classclass UserValidatorUserValidator implementsimplements ValidatorValidator { {

@Override@Override publicpublic booleanboolean supports(Class clazz)supports(Class clazz) { { returnreturn UserUser..classclass.isAssignableFrom(clazz);.isAssignableFrom(clazz); }}

publicpublic voidvoid validate(Object obj, validate(Object obj, ErrorsErrors errors) { errors) { UserUser user = ( user = (UserUser) obj;) obj;

ifif ((user.getEmailid() != "") || (user.getEmailid().length()) != 0) { ((user.getEmailid() != "") || (user.getEmailid().length()) != 0) { Pattern p = Pattern.Pattern p = Pattern.compilecompile(".+@.+\\.[a-z]+");(".+@.+\\.[a-z]+"); Matcher m = p.matcher(user.getEmailid());Matcher m = p.matcher(user.getEmailid()); booleanboolean b = m.matches(); b = m.matches(); ifif (b != (b != truetrue) {) { errors.rejectValue("emailid", "error.is.not.valid",errors.rejectValue("emailid", "error.is.not.valid", "Email ID does not Valid ");"Email ID does not Valid "); }} }}

ifif ((user.getContact() != "") || (user.getContact().length()) != 0) { ((user.getContact() != "") || (user.getContact().length()) != 0) { Pattern pattern = Pattern.Pattern pattern = Pattern.compilecompile("\\d{1}-\\d{4}-\\d{6}");("\\d{1}-\\d{4}-\\d{6}"); Matcher matcher = pattern.matcher(user.getContact());Matcher matcher = pattern.matcher(user.getContact()); booleanboolean con = matcher.matches(); con = matcher.matches(); ifif (con != (con != truetrue) {) { errors.rejectValue("contact", "error.is.not.valid",errors.rejectValue("contact", "error.is.not.valid", "Enter Contact Number Like 0-9999-999999");"Enter Contact Number Like 0-9999-999999"); }} }}

ifif ((user.getDob() != "") || (user.getDob().length()) != 0) { ((user.getDob() != "") || (user.getDob().length()) != 0) {

Pattern pattern = Pattern.Pattern pattern = Pattern.compilecompile("\\d{2}/\\d{2}/\\d{4}");("\\d{2}/\\d{2}/\\d{4}");

Matcher matcher = pattern.matcher(user.getDob());Matcher matcher = pattern.matcher(user.getDob());

booleanboolean DOB = matcher.matches(); DOB = matcher.matches();

ifif (DOB != (DOB != truetrue) {) {

errors.rejectValue("dob", "error.is.not.valid",errors.rejectValue("dob", "error.is.not.valid",

"Enter Date of birth Like 01/02/1986 ");"Enter Date of birth Like 01/02/1986 ");

}}

}}

ifif (user.getName() == (user.getName() == nullnull || user.getName().length() == 0) { || user.getName().length() == 0) {

errors.rejectValue("name", "error.empty.field", "Please Enter Name");errors.rejectValue("name", "error.empty.field", "Please Enter Name");

}}

ifif (user.getDob() == (user.getDob() == nullnull || user.getDob().length() == 0) { || user.getDob().length() == 0) {

errors.rejectValue("dob", "error.empty.field",errors.rejectValue("dob", "error.empty.field",

"Please Enter Date Of Birth");"Please Enter Date Of Birth");

}}

ifif (user.getContact() == (user.getContact() == nullnull || user.getContact().length() == 0) { || user.getContact().length() == 0) {

errors.rejectValue("contact", "error.empty.field",errors.rejectValue("contact", "error.empty.field",

"Please Enter Contact Number");"Please Enter Contact Number");

}}

ifif (user.getEmailid() == (user.getEmailid() == nullnull || user.getEmailid().length() == 0) { || user.getEmailid().length() == 0) {

errors.rejectValue("emailid", "error.empty.field",errors.rejectValue("emailid", "error.empty.field",

"Please Enter Email ID");"Please Enter Email ID");

}}

ifif (user.getQualification() == (user.getQualification() == nullnull

|| user.getQualification().length() == 0) {|| user.getQualification().length() == 0) {

errors.rejectValue("qualification", "error.empty.field",errors.rejectValue("qualification", "error.empty.field",

"Please Enter Qualification");"Please Enter Qualification");

}}

ifif (user.getAddress() == (user.getAddress() == nullnull || user.getAddress().length() == 0) { || user.getAddress().length() == 0) {

errors.rejectValue("address", "error.empty.field",errors.rejectValue("address", "error.empty.field",

"Please Enter Address");"Please Enter Address");

}}

}}

}}

Page 42: Spring

SampleSample

SampleSample

Page 43: Spring

SampleSample

SampleSample

Page 44: Spring

SampleSample

SampleSample

Page 45: Spring

SampleSample

SampleSample

Page 46: Spring

Spring Transaction ManagementSpring Transaction ManagementThe 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.

Page 47: Spring

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.

Page 48: Spring

Transaction DenifitionTransaction DenifitionThe TransactionDefinition interface specifies:• Isolation: The degree to which this transaction is isolated from the work of other transactions. Forexample, 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 isexecuted when a transaction context already exists. For example, code can continue running in theexisting transaction (the common case); or the existing transaction can be suspended and a newtransaction 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 “Transactionpropagation”.• Timeout: How long this transaction runs before timing out and being rolled back automatically by theunderlying 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 usingHibernate.

These settings reflect standard transactional concepts. If necessary, refer to resources that discusstransaction isolation levels and other core transaction concepts. Understanding these concepts is essentialto using the Spring Framework or any transaction management solution.

Page 49: Spring

Transaction StatusThe 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.

Page 50: Spring

PlatformTransactionManager implementations normally require knowledge of the environmentin 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 theDataSource definition. It will look like this:<bean id="txManager"

class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean>

Page 51: Spring

Hibernate TMHibernate TMYou 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.

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

Page 52: Spring
Page 53: Spring
Page 54: Spring
Page 55: Spring
Page 56: Spring
Page 57: Spring
Page 58: Spring
Page 59: Spring
Page 60: Spring
Page 61: Spring
Page 62: Spring
Page 63: Spring
Page 64: Spring
Page 65: Spring
Page 66: Spring
Page 67: Spring
Page 68: Spring
Page 69: Spring
Page 70: Spring
Page 71: Spring
Page 72: Spring
Page 73: Spring
Page 74: Spring
Page 75: Spring
Page 76: Spring
Page 77: Spring
Page 78: Spring
Page 79: Spring
Page 80: Spring
Page 81: Spring
Page 82: Spring
Page 83: Spring
Page 84: Spring
Page 85: Spring
Page 86: Spring
Page 87: Spring
Page 88: Spring
Page 89: Spring
Page 90: Spring
Page 91: Spring