Está en la página 1de 98

Spring

Ravikumar Maddi

What is the Benefits/Advantages of Using Spring Framework ? * Lightweight container * No App Server Dependent ? like EJB JNDI Calls Objects are created Lazily , Singleton - configuration * Components can added Declaratively * Initialization of properties is easy ? no need to read from properties file * Declarative transaction, security and logging service - AOP * application code is much easier to unit test With a Dependency Injection approach, dependencies are explicit, and evident in constructor or JavaBean properties * Spring's configuration management services can be used in any architectural layer, in whatever runtime environment. * Spring can effectively organize your middle tier objects * requires no special deployment steps

This is a list of new features for Spring 3.0. We will cover these features in more detail later in this section.  Spring Expression Language  IoC enhancements/Java based bean metadata  General-purpose type conversion system and field formatting system  Object to XML mapping functionality (OXM) moved from Spring Web Services project  Comprehensive REST support  @MVC additions  Declarative model validation  Early support for Java EE 6  Embedded database support

MessageSource


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

Example
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames"> <list> <value>applicationprop</value> </list> </property> <bean> <!-- let's inject the above MessageSource into this POJO --> <!---> <bean id="example" class="com.techfaq.Example"> <property name="messages" ref="messageSource"/> </bean> --------------------------------------------------------------------------------------------------------------------public class Example { private MessageSource messages; public void setMessages(MessageSource messages) { this.messages = messages; } public void execute() { String message = this.messages.getMessage("user.required", new Object [] {"UserName"}, "Required", null); System.out.println(message); message = this.messages.getMessage("passwd.required",null, "Required", null); System.out.println(message); } }

applicationprop.properties file in classpath. # in 'applicationprop.properties' passwd.required=Password Required! user.required= '{0}' is required. out put is : Password Required! UserName is required.

Constructor Ingection
<?xml version="1.0" encoding="UTF-8"?> encoding="UTF<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchemaxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/springhttp://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/springhttp://www.springframework.org/schema/util/spring-util.xsd"> <bean id="encyclopedia" name="mybean" class="Configure"> class="Configure"> <constructor<constructor-arg> <util:map> <entry key="CompanyName" value="Roseindia.net"/> <entry key="Address" value="Rohini"/> </util:map> </constructor-arg> </constructor</bean> <bean id="company" class="Companyinformation"> class="Companyinformation"> <property name="encyclopedia" ref="mybean"/> </bean> </beans>

public class Main { public static void main(String[] a) { XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("context.xml")); XmlBeanFactory( new company mycomp = (company) beanFactory.getBean("company"); System.out.println("Name of the company is: " + mycomp.Name()); System.out.println("Address of the company is: " + mycomp.address()); } } interface company { String Name(); String address(); } interface Detail { String find(String entry); } class Companyinformation implements company { private Detail detail; public String Name() { String name = this.detail.find("CompanyName"); this.detail.find("CompanyName"); return String.valueOf(name); } public String address() { String add = this.detail.find("Address"); this.detail.find("Address"); return String.valueOf(add); } public void setEncyclopedia(Detail d) { } class Configure implements Detail { private Map map; public Configure(Map map) { Assert.notNull(map, "Arguments cannot be null."); this.map this.map = map; } public String find(String s) { return (String) this.map.get(s); this.map.get(s); } } this.detail this.detail = d; }

Spring MVC
In web.xml file
<web<web-app> <servlet> <servlet-name>test</servlet<servlet-name>test</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on<load-on-startup>1</load-on-startup> </servlet> <servlet<servlet-mapping> <servlet-name>test</servlet<servlet-name>test</servlet-name> <url-pattern>*.do</url<url-pattern>*.do</url-pattern> </servlet</servlet-mapping> </web</web-app>

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

test-servlet.xml file test test-servlet.xml file contains viewResolver , Handler mappings testand Controllers.  viewResolver : All controllers in the Spring Web MVC framework return a ModelAndView instance.  Views in Spring are addressed by a view name and are resolved by a view resolver. For Example : if your controller return new ModelAndView("empform"); means control forwared to "/WEB-INF/jsp/empform.jsp" based on below "/WEBconfiguration. When returning "empform" as a viewname, this view resolver will hand the request over to the RequestDispatcher that will send the request to /WEB-INF/jsp/empform.jsp. /WEB-

BeanNameUrlHandlerMapping
A very simple, but very powerful handler mapping is the BeanNameUrlHandlerMapping, which maps incoming HTTP requests to names of beans, defined in the web application context.
<bean id="defaultHandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> Controllers :
<bean name="/test/empform.do" <bean name="/test/saveempform.do" class="com.EmpFormController"/> class="com.EmpSaveController"/>

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

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

import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; public class EmpSaveController implements Controller
{ public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception { System.out.println("inside EmpSaveController"); String firstName = request.getParameter("firstName"); System.out.println("firstName"+firstName); String lastName = request.getParameter("lastName"); System.out.println("lastName"+lastName); return new ModelAndView("success"); //RequestDispatcher that will send the request to /WEB-INF/jsp/success.jsp /WEB}

empform.jsp : <form method="POST" action="/springtest/test/saveempform.do"> First Name: <input name="firstName" type="text" value=""/> Last Name: <input name="lastName" type="text" value=""/> <input type="submit" value="Save Changes" /> </form> success.jsp : <h2>Emp name saved </h2>

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

import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; public class LogonController extends SimpleFormController { public Object formBackingObject(HttpServletRequest request) throws ServletException { UserBean backingObject = new UserBean(); System.out.println("formBackingObject"); /* The backing object should be set up here, with data for the initial values * of the forms fields. This could either be hard-coded, or retrieved from a hard* database. */ return backingObject; } public ModelAndView onSubmit(Object command) throws ServletException { UserBean user = (UserBean)command; System.out.println("username :"+user.getUserName()); System.out.println("password :"+user.getPassword()); //Now you can validate to database return new ModelAndView("succes"); }

import org.springframework.validation.Errors; import org.springframework.validation.Validator; public class LogonFormValidator implements Validator { public boolean supports(Class clazz) { return clazz.equals(UserBean.class); clazz.equals(UserBean.class); } public void validate(Object obj, Errors errors) { UserBean user = (UserBean) obj; if (user == null) { null) errors.rejectValue("username", "error.login.not-specified", null, "error.login.notnull, "Value required."); } else { if (user.getUserName() == null || user.getUserName().trim().length() <= 0) { System.out.println("user System.out.println("user name null value"); errors.rejectValue("userName", "error.login.invalid-user", "error.login.invalidnull, null, "Username is Required."); } else { if (user.getPassword() == null || user.getPassword().trim().length() <= 0) { errors.rejectValue("password", "error.login.invalid-pass", "error.login.invalidnull, null, "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; } }

logonForm.jsp
<%@ taglib prefix="core" uri="http://java.sun.com/jstl/core"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt"%> <%@ taglib prefix="str" uri="http://jakarta.apache.org/taglibs/string-1.1"%> <%@ taglib prefix="spring" uri="/spring"%> <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>

Success.jsp: <h2>Login Success </h2>

MultiActionController
<bean id="viewResolver" id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> name="prefix"> <value>/WEB-INF/jsp/</value> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> name="suffix"> <value>.jsp</value> <value>.jsp</value> </property> </bean> <bean name="/*.html" class=com.MultiActionControllerExample" /> name="/*.html" class=com.MultiActionControllerExample" </beans> Index.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> contentType="text/html" pageEncoding="UTF-8"%> <html> <head> <title>Multi <title>Multi Action Controller Example</title> </head> <body> <h4>Multi <h4>Multi Action Controller Example</h4> <a href="add.html" >Add</a> <br/> href="add.html" <a href="update.html" >Update</a><br/> href="update.html" <a href="edit.html" >Edit</a> <br/> href="edit.html" <a href="remove.html" >Remove</a> href="remove.html" </body> </html> showmessage.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" charset=ISO-8859pageEncoding="ISO-8859pageEncoding="ISO-8859-1"%> <html><head> <title>Success Page</title> </head> <body> ${message} </body> </html>

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

package com; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; public class MultiActionControllerExample extends MultiActionController { public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception { return new ModelAndView("showmessage", "message", "Add method called"); } public ModelAndView update(HttpServletRequest request, HttpServletResponse response) throws Exception { return new ModelAndView("showmessage", "message", "Update method called"); } public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) throws Exception { return new ModelAndView("showmessage", "message", "Edit method called"); } public ModelAndView remove(HttpServletRequest request, HttpServletResponse response) throws Exception { return new ModelAndView("showmessage", "message", "Remove method called"); } }

Spring Multi-Action Using Annotation Tutorial MultiLearn how to group multiple actions into a single controller using Spring Annotation. To group related actions into a single controller class using Spring annotations use the @RequestMapping annotation at the method level instead of class level. The UserController class with the add() and the remove() method is shown below. 01.package com.tutorials4u.web; 02. 03.import org.springframework.stereotype.Controller; 04.import org.springframework.web.bind.annotation.RequestMapping; 05.import org.springframework.web.servlet.ModelAndView; 06. 07.@Controller 08.public class UserController { 09. 10. @RequestMapping("/user/add.htm") 11. public ModelAndView add() { 12. System.out.println("Add method called"); 13. return new ModelAndView("user", "message", "Add method called"); 14. } 15. 16. @RequestMapping("/user/remove.htm") 17. public ModelAndView remove() { 18. System.out.println("Remove method called"); 19. return new ModelAndView("user", "message", "Remove method called"); 20. } 21.} To handle multiple action in a single controller class, that is the only change you need to do. In the redirect.jsp page we have two urls one to call the add() method and the other to call the remove() method.

Spring Annotation Based Controller Tutorial


Learn how to handle forms using Spring annotation based controller class. In this example you will see how to populate a form using Spring annotations. The annotated user controller class is shown below. 01.package com.tutorials4u.web; 02. 03.import java.util.List; 04. 05.import org.springframework.beans.factory.annotation.Autowired; 06.import org.springframework.stereotype.Controller; 07.import org.springframework.ui.ModelMap; 08.import org.springframework.web.bind.annotation.ModelAttribute; 09.import org.springframework.web.bind.annotation.RequestMapping; 10.import org.springframework.web.bind.annotation.RequestMethod; 11.import org.springframework.web.bind.annotation.SessionAttributes; 12. 13.import com.tutorials4u.domain.Community; 14.import com.tutorials4u.domain.Country; 15.import com.tutorials4u.domain.User; 16.import com.tutorials4u.service.UserService; 17. 18.@Controller 19.@RequestMapping("/userRegistration.htm") 20.@SessionAttributes("user") 21.public class UserController { 22. 23. private UserService userService; 24. 25. @Autowired 26. public void setUserService(UserService userService) { 27. this.userService = userService; 28. } 29. 30. @ModelAttribute("countryList") 31. public List<Country> populateCountryList() { 32. return userService.getAllCountries(); 33. } 34. 35. @ModelAttribute("communityList") 36. public List<Community> populateCommunityList() { 37. return userService.getAllCommunities(); 38. } 39. 40. @RequestMapping(method = RequestMethod.GET) 41. public String showUserForm(ModelMap model) { 42. User user = new User(); 43. model.addAttribute("user", user); 44. return "userForm"; 45. } 46. 47. @RequestMapping(method = RequestMethod.POST) 48. public String onSubmit(@ModelAttribute("user") User user) { 49. userService.add(user); 50. return "redirect:userSuccess.htm"; 51. } 52. 53.}

Spring Annotation Based Controller Tutorial The populateCountryList() and populateCommunityList() methods are used to populate the country and community list respectively. The @ModelAttribute annotation when used at the method level is used to indicate that the method contain reference data used by the model, so it should be called before the form is loaded. This is similar to overriding the referenceData() method when extending the SimpleFormController. SimpleFormController. You can also do this in the showUserForm() method like this. 1. @RequestMapping(method = RequestMethod.GET) 2. public String showUserForm(ModelMap model) { 3. User user = new User(); 4. model.addAttribute(userService.getAllCountries()); 5. model.addAttribute(userService.getAllCommunities()); 6. model.addAttribute("user", user); 7. return "userForm"; 8.} Since we use ModelMap here by default the names of the list will be countryList and communityList. communityList.

Spring Multi-Action Using Annotation Tutorial MultiLearn how to group multiple actions into a single controller using Spring Annotation. To group related actions into a single controller class using Spring annotations use the @RequestMapping annotation at the method level instead of class level. The UserController class with the add() and the remove() method is shown below. 01.package com.tutorials4u.web; 02. 03.import org.springframework.stereotype.Controller; 04.import org.springframework.web.bind.annotation.RequestMapping; 05.import org.springframework.web.servlet.ModelAndView; 06. 07.@Controller 08.public class UserController { 09. 10. @RequestMapping("/user/add.htm") 11. public ModelAndView add() { 12. System.out.println("Add method called"); 13. return new ModelAndView("user", "message", "Add method called"); 14. } 15. 16. @RequestMapping("/user/remove.htm") 17. public ModelAndView remove() { 18. System.out.println("Remove method called"); 19. return new ModelAndView("user", "message", "Remove method called"); 20. } 21.} To handle multiple action in a single controller class, that is the only change you need to do. In the redirect.jsp page we have two urls one to call the add() method and the other to call the remove() method.

Spring Hibernate
<beans> <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> destroy<property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/> <property name="username" value="sa"/> <property name="password" value="sa"/> </bean> <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="myDataSource"/> <property name="mappingResources"> <list> <value>emp.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.HSQLDialect </value> </property> </bean> </beans>

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

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

EmpDAO.java class public class EmpDAO { private HibernateTemplate hibernateTemplate; public void setSessionFactory(SessionFactory sessionFactory) { this.hibernateTemplate = new HibernateTemplate(sessionFactory); } public Collection getEmpByDept(String dept) throws DataAccessException { return this.hibernateTemplate.find("from com.bean.Emp e where e.dept=?", dept); } }

HibernateDaoSupport
HibernateDaoSupport base class offers methods to access the current transactional Session. EmpDAO.java class public class EmpDAO extends HibernateDaoSupport { public Collection getEmpByDept(String dept) throws DataAccessException, MyException { Session session = getSession(false); try { Query query = session.createQuery("from com.bean.Emp e where e.dept=?"); query.setString(0, dept); List result = query.list(); if (result == null) { throw new MyException("No results."); } return result; } catch (HibernateException ex) { throw convertHibernateAccessException(ex); } } }

Inheritence
context.xml <?xml version="1.0" encoding="UTF-8"?> encoding="UTF<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchemaxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/springhttp://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="parent" class="mybean" > class="mybean" <property name="name" value="Roseindia.net"/> </bean> <bean id="child" class="mybean" parent="parent"> class="mybean" <property name="address" value="Rohini"/> </bean> <bean id="subchild" class="mybean" parent="parent"/> class="mybean" </beans>

import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Main { public static void main(String[] args) throws Exception { XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("context.xml")); XmlBeanFactory(new System.out.println("===============Inheritance demo================="); System.out.println(bf.getBean("child")); System.out.println(bf.getBean("subchild")); } } class mybean { private String name; private String address; public void setName(String name) { this.name this.name = name; } public void setAddress(String address) { this.address this.address = address; } @Override public String toString() { final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Bean"); stringBuilder.append("{name='").append(name).append('\ stringBuilder.append("{name='").append(name).append('\''); stringBuilder.append(", address=").append(address); stringBuilder.append('}'); return stringBuilder.toString(); } } Output: Nov 25, 2008 3:39:29 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReade r loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [context.xml] ===============Inheritance demo================= Bean{name='Roseindia.net', address=Rohini} Bean{name='Roseindia.net', address=null} BUILD SUCCESSFUL (total time: 1 second)

Property injection
<?xml version="1.0" encoding="UTF-8"?> encoding="UTF<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchemaxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/springhttp://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="mybean" class="Inject" class="Inject" p:name="Girish" p:age="24" p:address="Noida" p:company="Roseindia.net" p:email="girish@roseindia.net"/> </beans>

import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Main { public static void main(String[] args) { XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource( XmlBeanFactory(new "context.xml")); Inject demo = (Inject) beanFactory.getBean("mybean"); System.out.println(demo); } } class Inject { private private private private private String name; int age; String company; String email; String address;

public void setAddress(String address) { this.address this.address = address; } public void setCompany(String company) { this.company this.company = company; } public void setEmail(String email) { this.email this.email = email; } public void setAge(int age) { setAge(int this.age this.age = age; } public void setName(String name) { this.name this.name = name; } @Override public String toString() { return String.format("Name: %s\n" + %s\ "Age: %d\n" + %d\ "Address: %s\n" + %s\ "Company: %s\n" + %s\ "E"E-mail: %s", this.name, this.age, this.address, this.company, this.email); this.name, this.age, this.address, this.company, this.email); } }

This controller is use to redirect the page in the Spring 2.5 Web MVC applications. This controller doesn't require controller class. This controller provides an alternative to sending a request straight to a view such as a JSP. we will configure just declared the ParameterizableViewController bean and set the view name through the "viewName" property. "viewName" Now we will used ParameterizedViewController for control the behavior of the application. Example: 1) index.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> contentType="text/html" pageEncoding="UTF-8"%> <a href="parameterizableviewcontroller.html">ParameterizableViewController Example</a> href="parameterizableviewcontroller.html">ParameterizableViewController

<?xml version="1.0" encoding="UTF-8"?> version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchemaxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> name="mappings"> <props> <prop key="/parameterizableviewcontroller.html">parameterizableController</prop> key="/parameterizableviewcontroller.html">parameterizableController</prop> </props> </property> </bean> <bean name="parameterizableController name="parameterizableController class="org.springframework.web.servlet.mvc.ParameterizableViewController"> class="org.springframework.web.servlet.mvc.ParameterizableViewController"> <property name="viewName" value="ParameterizableController" /> name="viewName" value="ParameterizableController" </bean> <bean id="viewResolver class="org.springframework.web.servlet.view.InternalResourceViewResolver" > id="viewResolver class="org.springframework.web.servlet.view.InternalResourceViewResolver" <property name="prefix"> name="prefix"> <value>/WEB<value>/WEB-INF/jsp/</value> </property> <property name="suffix"> name="suffix"> <value>.jsp</value> </property> </bean> </beans>

UMLFilenameViewController
If user don't want to include any logical operation on request and redirect to some resource then user used UrlFilenameViewController that's transform the virtual path of a URL into a view name and provide a view to display as a user interface. In this example we will discuss about UrlFileNameViewController. <?xml version="1.0" encoding="UTF-8"?> version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchemaxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="staticViewController" class="org.springframework.web.servlet.mvc.UrlFilenameViewController"/> id="staticViewController" class="org.springframework.web.servlet.mvc.UrlFilenameViewController" <bean id="urlMapping class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> id="urlMapping class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="interceptors"> name="interceptors"> <list> <ref local="localeChangeInterceptor"/> local="localeChangeInterceptor"/> </list> </property> <property name="urlMap"> name="urlMap"> <map> <entry key="/*.html"> key="/*.html"> <ref bean="staticViewController"/> bean="staticViewController" </entry> </map> </property> </bean> <bean id="viewResolver class="org.springframework.web.servlet.view.InternalResourceViewResolver"> id="viewResolver class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> name="prefix"> <value>/WEB<value>/WEB-INF/</value> </property> <property name="suffix"> name="suffix"> <value>.jsp</value> <value>.jsp</value> </property> </bean>

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

AbstractWizardFormController


Spring Web MVC provides AbstractWizardFormController class that handle wizard form. In this tutorial, we will used AbstractWizardFormController class. The AbstractWizardFormController class provide us to store and show the forms data with multiple pages. It manage the navigation between pages and validate the user input data form a single page of the whole model object at once. In this tutorial we will discuss about this controller.

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

<?xml version="1.0" encoding="UTF-8"?> version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/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="http://www.springframework.org/schema/beans xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" xmlns:p="http://www.springframework.org/schema/p"> xmlns:p="http://www.springframework.org/schema/p"> <bean id="urlMapping class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> id="urlMapping class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" <property name="interceptors"> name="interceptors"> <list> <ref local="localeChangeInterceptor"/> </list> local="localeChangeInterceptor"/> </property> <property name="urlMap"> name="urlMap"> <map> <entry key="/user1.html"> key="/user1.html" <ref bean="wizardController"/></entry> bean="wizardController" </map> </property></bean> <bean id="wizardController" class=com.AWizardFormController"> id="wizardController" class=com.AWizardFormController" <property name="commandName"><value>user</value></property> name="commandName"><value>user</value></property> <property name="commandClass"><value>net.roseindia.web.User</value></property> name="commandClass"><value>net.roseindia.web.User</value></property> <property name="pages"><value>user1,user2,user3</value></property> name="pages"><value>user1,user2,user3</value></property> <property name="pageAttribute"><value>page</value></property> name="pageAttribute"><value>page</value></property> </bean> <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <property name="paramName" value="hl"/> name="paramName" value="hl"/> </bean> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/> id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/> <bean id="viewResolver class="org.springframework.web.servlet.view.InternalResourceViewResolver"> id="viewResolver class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> name="prefix"> <value>/WEB-INF/jsp/</value> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> name="suffix"> <value>.jsp</value> <value>.jsp</value> </property> </bean> </beans>

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

User2.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" charset=ISO-8859pageEncoding="ISO-8859pageEncoding="ISO-8859-1"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%> <html><head><title>Second Entry</title></head> <body> <form:form method="POST" commandName="user"> <center><table><tr><td align="right" width="20%"> <strong>Date of birth:</strong></td><td style="width: 50%"> <spring:bind path="user.dob"> <input type="text" name="dob" value="<c:out value="${status.value}"/>"/> </spring:bind></td><td><font color="red"> <form:errors path="dob"/></font></td></tr><tr><td align="right" width="20%"> <strong>Address:</strong></td><td style="width: 50%"> <spring:bind path="user.address"> <input type="text" name="address" value="<c:out value="${status.value}"/>"/> </spring:bind></td><td> <font color="red"><form:errors path="address"/></font></td></tr><tr><td align="right" width="20%"> <strong>Country:</strong></td><td style="width: 50%"> <spring:bind path="user.country"> <input type="text" name="country" value="<c:out value="${status.value}"/>"/> </spring:bind></td><td><font color="red"> <form:errors path="country"/></font></td></tr><tr><td align="right" width="20%"> <strong>Qualification:</strong></td><td style="width: 50%"> <spring:bind path="user.qualification"> <input type="text" name="qualification" value="<c:out value="${status.value}"/>"/> </spring:bind></td><td><font color="red"> <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="_target2" value="Next"/> <input type="submit" name="_cancel" value="Cancle"/> <input type="submit" name="_target2" value="Finish"/></td></tr></table> </center></form:form></body></html>

public class User { private String private String private String private String private String private String private String private String private String firstName; lastName; emailId; contact; gender; dob; address; country; qualification;

User3.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859- pageEncoding="ISO-8859charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%> <html><head><title>Show Details</title></head> <body> <form:form method="POST" commandName="user"> <center><table><tr><td style="width: 56%" colspan="2"> <strong>The Values entered are as follow</strong></td></tr><tr><td align="right" width="20%"> <strong>First Name:</strong></td><td style="width: 56%"> ${user.firstName}</td></tr><tr><td align="right" width="20%"> <strong>Last Name:</strong></td><td style="width: 56%"> ${user.lastName}</td></tr><tr><td align="right" width="20%"> <strong>Email Id:</strong></td><td style="width: 56%"> ${user.emailId}</td></tr><tr><td align="right" width="20%"> <strong>Contact:</strong></td><td style="width: 56%"> ${user.contact}</td></tr><tr><td align="right" width="20%"> <strong>Gender:</strong></td><td style="width: 56%"> ${user.gender}</td></tr><tr><td align="right" width="20%"> <strong>Date of Birth:</strong></td><td style="width: 56%"> ${user.dob}</td></tr><tr><td align="right" width="20%"> <strong>Address:</strong></td><td style="width: 56%"> ${user.address}</td></tr><tr><td align="right" width="20%"> <strong>Country:</strong></td><td style="width: 56%"> ${user.country}</td></tr><tr><td align="right" width="20%"> <strong>Qualification:</strong></td><td style="width: 56%"> ${user.qualification}</td></tr></table></center> </form:form></body></html>

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

import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; javax.servlet.http.HttpServletResponse; import org.springframework.validation.BindException; org.springframework.validation.BindException; import org.springframework.validation.Errors; org.springframework.validation.Errors; import org.springframework.web.servlet.ModelAndView; org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractWizardFormController; org.springframework.web.servlet.mvc.AbstractWizardFormController; import org.springframework.web.servlet.view.RedirectView; org.springframework.web.servlet.view.RedirectView; import net.roseindia.web.User; net.roseindia.web.User; public class AWizardFormController extends AbstractWizardFormController { @Override protected ModelAndView processCancel(HttpServletRequest request, processCancel(HttpServletRequest HttpServletResponse response, Object command, BindException errors) throws Exception { // Logical code System.out.println("processCancel"); System.out.println("processCancel"); return new ModelAndView(new RedirectView("user1.html")); ModelAndView( RedirectView("user1.html")); } @Override protected ModelAndView processFinish(HttpServletRequest request, processFinish(HttpServletRequest HttpServletResponse response, Object command, BindException errors) throws Exception { // Logical code System.out.println("processFinish"); System.out.println("processFinish"); return new ModelAndView(new RedirectView("user4.html")); ModelAndView( RedirectView("user4.html")); } protected void validatePage(Object command, Errors errors, int page) { (User) User user = (User) command; if (page == 0) { if (user.getFirstName() == "") { errors.rejectValue("firstName", "error.too-high", null, "error.toonull, "First Name cannot be empty."); } if (user.getLastName() == "") { errors.rejectValue("lastName", "error.too-high", null, "error.toonull, "Last Name cannot be empty."); } if (user.getEmailId() == "") { errors.rejectValue("emailId", "error.too-high", null, "error.toonull, "EmailId cannot be empty."); } if ((user.getEmailId() != "") || (user.getEmailId().length()) != 0) { Pattern p = Pattern.compile(".+@.+\\.[a-z]+"); Pattern.compile(".+@.+\ .[aMatcher m = p.matcher(user.getEmailId()); boolean b = m.matches();
} }

if (b != true) { true) errors.rejectValue("emailId", "error.is.not.valid", "Email ID does not Valid "); } } if (user.getContact() == "") { errors.rejectValue("contact", "error.too-high", null, "error.toonull, "Contact cannot be empty."); } if ((user.getContact() != "") || (user.getContact().length()) != 0) { Pattern pattern = Pattern.compile("\\d{1}-\\d{4}-\\d{6}"); Pattern.compile("\ d{1}- d{4}Matcher matcher = pattern.matcher(user.getContact()); boolean con = matcher.matches(); if (con != true) { true) errors.rejectValue("contact", "error.is.not.valid", "Enter Contact Number Like 0-9999-999999"); 0-9999} } if (user.getGender() == "") { errors.rejectValue("gender", "error.too-high", null, "error.toonull, "Gender cannot be empty."); } } if (page == 1) { if (user.getDob() == "") { errors.rejectValue("dob", "error.too-high", null, "error.toonull, "Date of birth cannot be empty."); } if ((user.getDob() != "") || (user.getDob().length()) != 0) { Pattern pattern = Pattern.compile("\\d{2}/\\d{2}/\\d{4}"); Pattern.compile("\ d{2}/\ d{2}/\ Matcher matcher = pattern.matcher(user.getDob()); boolean DOB = matcher.matches(); if (DOB != true) { true) errors.rejectValue("dob", "error.is.not.valid", "Enter Date of birth Like 01/02/1986 "); } } if (user.getAddress() == "") { errors.rejectValue("address", "error.too-high", null, "error.toonull, "Address cannot be empty."); } if (user.getCountry() == "") { errors.rejectValue("country", "error.too-high", null, "error.toonull, "Country cannot be empty."); } if (user.getQualification() == "") { errors.rejectValue("qualification", "error.too-high", null, "error.toonull, "Qualification cannot be empty."); } }

SimpleFromController
Spring provides SimpleFromController for control a form data in the web application. If you want to handle form in spring then then you need to use SimpleFormController by extending these in your Controller class. It's provides formView, successView in the case of valid submission and provide validation errors if wrong data entry by the user in the form data. This is also handle handle model object for binding and fetching data. In this example we will discuss about SimpleFormController work flow. In this example we will create a form that accept user data and display Index.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> contentType="text/html" pageEncoding="UTF-8"%> <html><head><title>User Welcome Page</title></head> <body bgcolor="#EEEEEE"> bgcolor="#EEEEEE"> <center> <a href="user.html">Fill User Personal Details</a> href="user.html">Fill </center></body></html>

<?xml version="1.0" encoding="UTF-8"?> version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchemaxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" http://www.springframework.org/schema/beans/spring-beansxmlns:p="http://www.springframework.org/schema/p"> xmlns:p="http://www.springframework.org/schema/p"> <bean id="viewResolver class="org.springframework.web.servlet.view. id="viewResolver class="org.springframework.web.servlet.view. InternalResourceViewResolver"> InternalResourceViewResolver"> <property name="prefix"> name="prefix"> <value>/WEB<value>/WEB-INF/jsp/</value> </property> <property name="suffix"> name="suffix"> <value>.jsp</value> </property> </bean> <bean id="urlMapping" id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerM class="org.springframework.web.servlet.handler.SimpleUrlHandlerM apping"> apping"> <property name="interceptors"> name="interceptors"> <list> <ref local="localeChangeInterceptor" /> local="localeChangeInterceptor" </list> </property> <property name="urlMap"> name="urlMap"> <map> <entry key="/user.html"> key="/user.html"> <ref bean="userController" /> bean="userController" </entry> </map> </property> </bean> <bean id="userValidator" class="net.roseindia.web.UserValidator" /> id="userValidator" class="net.roseindia.web.UserValidator"

<bean id="userController" class="net.roseindia.web.UserFormController"> id="userController" class="net.roseindia.web.UserFormController"> <property name="sessionForm"> name="sessionForm"> <value>false</value> </property> <property name="commandName"> name="commandName"> <value>user</value> </property> <property name="commandClass"> name="commandClass"> <value>net.roseindia.web.User</value> </property> <property name="validator"> name="validator"> <ref bean="userValidator" /> bean="userValidator" </property> <property name="formView"> name="formView"> <value>user</value> </property> <property name="successView"> name="successView"> <value>usersuccess</value> </property> </bean> <bean id="localeChangeInterceptor" id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <property name="paramName" value="hl" /> name="paramName" value="hl" </bean> <bean id="localeResolver" id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" /> </beans>

User.jsp
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ taglib prefix="spring" uri="/spring"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html> <head> <title>User Personal Details</title> </head> <body> <center> <h3>User Personal Details</h3> <br /> <form:form commandName="user" method="POST" name="user"> commandName="user" method="POST" name="user"> <table border="0"> border="0"> <tr> <td>Name:</td> <td> <form:input path="name" /> path="name" </td> <td> <font color="red"> color="red"> <form:errors path="name" /> path="name" </font> </td> </tr> <tr> <td>Email ID:</td> <td> <form:input path="emailid" /> path="emailid" </td> <td> <font color="red"> color="red"> <form:errors path="emailid" /> path="emailid" </font> </td> </tr>

<tr> <td>Date of birth:</td> <td> <form:input path="dob" /> path="dob" </td> <td> <font color="red"> color="red"> <form:errors path="dob" /> path="dob" </font> </td> </tr> <tr> <td>Qualification:</td> <td> <form:input path="qualification" /> path="qualification" </td> <td> <font color="red"> color="red"> <form:errors path="qualification" /> path="qualification" </font> </td> </tr> <tr> <td>Contact Number:</td> <td> <form:input path="contact" /> path="contact" </td> <td> <font color="red"> color="red"> <form:errors path="contact" /> path="contact" </font> </td> </tr> <tr> <td>Address:</td> <td> <form:input path="address" /> path="address" </td> <td> <font color="red"> color="red"> <form:errors path="address" /> path="address" </font> </td> </tr> <tr> <td colspan="3" align="center"> colspan="3" align="center"> <input type="submit" value="Save" /> type="submit" value="Save" </td> </tr> </table> </form:form> </center> </body> </html>

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

<tr> <td>Qualification:</td> <td> <core:out value="${user.qualification}" /> value="${user.qualification}" </td> </tr> <tr> <td>Contact Number:</td> <td> <core:out value="${user.contact}" /> value="${user.contact}" </td> </tr> <tr> <td>Address:</td> <td> <core:out value="${user.address}" /> value="${user.address}" </td> </tr> </table> <a href="user.html">Back</a> href="user.html">Back</a> </center> </body> </html>

public class User { public User(){}

package net.roseindia.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.ServletException; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectVi ew; import org.springframework.web.servlet.mvc.SimpleFor mController; import net.roseindia.web.User; @SuppressWarnings("deprecation") public class UserFormController extends SimpleFormCo ntroller { @Override protected ModelAndView onSubmit(Object command) t hrows ServletException { User user = (User) command; ModelAndView modelAndView = new ModelAndView (getSuccessView()); modelAndView.addObject("user", user); return modelAndView; } }

private String name; private String emailid; private String dob; private String address; private String qualification; private String contact;
public String getDob() { return dob; } public void setDob(String dob) { this.dob this.dob = dob; } public String getQualification() { return qualification; } public void setQualification(String qualification) { this.qualification this.qualification = qualification; } public String getContact() { return contact; } public void setContact(String contact) { this.contact this.contact = contact; } public String getName() { return name; } public void setName(String name) { this.name this.name = name; } public String getEmailid() { return emailid; } public void setEmailid(String emailid) { this.emailid this.emailid = emailid; } public String getAddress() { return address; } public void setAddress(String address) { this.address this.address = address; }

package net.roseindia.web; net.roseindia.web; import java.util.regex.*; import org.springframework.validation.Errors; org.springframework.validation.Errors; import org.springframework.validation.Validator; org.springframework.validation.Validator; import net.roseindia.web.User; net.roseindia.web.User; public class UserValidator implements Validator { @Override public boolean supports(Class clazz) { return User.class.isAssignableFrom(clazz); User.class.isAssignableFrom(clazz); } public void validate(Object obj, Errors errors) { (User) User user = (User) obj; if ((user.getEmailid() != "") || (user.getEmailid().length()) != 0) { Pattern p = Pattern.compile(".+@.+\\.[a-z]+"); Pattern.compile(".+@.+\ .[aMatcher m = p.matcher(user.getEmailid()); boolean b = m.matches(); if (b != true) { true) errors.rejectValue("emailid", "error.is.not.valid", "Email ID does not Valid "); } } if ((user.getContact() != "") || (user.getContact().length()) != 0) { Pattern pattern = Pattern.compile("\\d{1}-\\d{4}-\\d{6}"); Pattern.compile("\ d{1}- d{4}Matcher matcher = pattern.matcher(user.getContact()); boolean con = matcher.matches(); if (con != true) { true) errors.rejectValue("contact", "error.is.not.valid", "Enter Contact Number Like 0-9999-999999"); 0-9999} }

if ((user.getDob() != "") || (user.getDob().length()) != 0) { Pattern pattern = Pattern.compile("\\d{2}/\\d{2}/\\d{4}"); Pattern.compile("\ d{2}/\ d{2}/\ Matcher matcher = pattern.matcher(user.getDob()); boolean DOB = matcher.matches(); if (DOB != true) { true) errors.rejectValue("dob", "error.is.not.valid", "Enter Date of birth Like 01/02/1986 "); } } if (user.getName() == null || user.getName().length() == 0) { errors.rejectValue("name", "error.empty.field", "Please Enter Name"); } if (user.getDob() == null || user.getDob().length() == 0) { errors.rejectValue("dob", "error.empty.field", "Please Enter Date Of Birth"); } if (user.getContact() == null || user.getContact().length() == 0) { errors.rejectValue("contact", "error.empty.field", "Please Enter Contact Number"); } if (user.getEmailid() == null || user.getEmailid().length() == 0) { errors.rejectValue("emailid", "error.empty.field", "Please Enter Email ID"); } if (user.getQualification() == null || user.getQualification().length() == 0) { errors.rejectValue("qualification", "error.empty.field", "Please Enter Qualification"); } if (user.getAddress() == null || user.getAddress().length() == 0) { errors.rejectValue("address", "error.empty.field", "Please Enter Address"); } } }

Sample Sample

Sample Sample

Sample Sample

Sample Sample

Spring Transaction Management


The key to the Spring transaction abstraction is the notion of a transaction strategy. A transaction strategy is defined by the org.springframework.transaction.PlatformTransactionManager interface:
public interface PlatformTransactionManager { TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException; void commit(TransactionStatus status) throws TransactionException; void rollback(TransactionStatus status) throws TransactionException; }

This is primarily a service provider interface (SPI), although it can be used programmatically from your application code. Because PlatformTransactionManager is an interface, it can be easily mocked or stubbed as necessary. It is not tied to a lookup strategy such as JNDI. PlatformTransactionManager implementations are defined like any other object (or bean) in the Spring Framework IoC container. This benefit alone makes Spring Framework transactions a worthwhile abstraction even when you work with JTA. Transactional code can be tested much more easily than if it used JTA directly.

Again in keeping with Spring's philosophy, the TransactionException that can be thrown by any of the PlatformTransactionManager interface's methods is unchecked (that is, it extends thejava.lang.RuntimeException class). Transaction infrastructure failures are almost invariably fatal. In rare cases where application code can actually recover from a transaction failure, the application developer can still choose to catch and handle TransactionException. The salient point is that developers are not forced to do so. The getTransaction(..) method returns a TransactionStatus object, depending on a TransactionDefinition parameter. The returned TransactionStatus might represent a new transaction, or can represent an existing transaction if a matching transaction exists in the current call stack. The implication in this latter case is that, as with Java EE transaction contexts, a TransactionStatus is associated with a thread of execution.

Transaction Denifition
The TransactionDefinition interface specifies: Isolation: The degree to which this transaction is isolated from the work of other transactions. For example, can this transaction see uncommitted writes from other transactions? Propagation: Typically, all code executed within a transaction scope will run in that transaction. However, you have the option of specifying the behavior in the event that a transactional method is executed when a transaction context already exists. For example, code can continue running in the existing transaction (the common case); or the existing transaction can be suspended and a new transaction created. Spring offers all of the transaction propagation options familiar from EJB CMT. To read about the semantics of transaction propagation in Spring, see the section called Transaction propagation. Timeout: How long this transaction runs before timing out and being rolled back automatically by the underlying transaction infrastructure. Read-only status: A read-only transaction can be used when your code reads but does not modify data. Read-only transactions can be a useful optimization in some cases, such as when you are using Hibernate. These settings reflect standard transactional concepts. If necessary, refer to resources that discuss transaction isolation levels and other core transaction concepts. Understanding these concepts is essential to using the Spring Framework or any transaction management solution.

Transaction Status
The TransactionStatus interface provides a simple way for transactional code to control transaction execution and query transaction status. The concepts should be familiar, as they are common to all transaction APIs:
public interface TransactionStatus extends SavepointManager {
boolean isNewTransaction(); boolean hasSavepoint(); void setRollbackOnly(); boolean isRollbackOnly(); void flush(); boolean isCompleted();

Regardless of whether you opt for declarative or programmatic transaction management in Spring, defining the correct PlatformTransactionManager implementation is absolutely essential. You typically define this implementation through dependency injection.

PlatformTransactionManager implementations normally require knowledge of the environment in which they work: JDBC, JTA, Hibernate, and so on. The following examples show how you can define a local PlatformTransactionManager implementation. (This example works with plain JDBC.) You define a JDBC DataSource <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroymethod="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> The related The PlatformTransactionManager bean definition will then have a reference to the DataSource definition. It will look like this: <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean>

Hibernate TM
You can also use Hibernate local transactions easily, as shown in the following examples. In this case, you need to define a Hibernate LocalSessionFactoryBean, which your application code will use to obtain Hibernate Session instances. The DataSource bean definition will be similar to the local JDBC example shown previously and thus is not shown in the following example. Note If the DataSource, used by any non-JTA transaction manager, is looked up via JNDI and managed by a Java EE container, then it should be non-transactional because the Spring Framework, rather than the Java EE container, will manage the transactions. The txManager bean in this case is of the HibernateTransactionManager type. In the same way as the DataSourceTransactionManager needs a reference to the DataSource, the HibernateTransactionManager needs a reference to the SessionFactory.
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mappingResources"> <list> <value>org/springframework/samples/petclinic/hibernate/petclinic.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=${hibernate.dialect} </value> </property> </bean> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean>

AOP
What is AOP - Aspect-oriented programming ? Aspectthe system service like logging, transaction management, security etc., must be included in the program in general case. AOP makes it possible to modularize and separate these services and then apply them declaratively to the components and we can focus on our own specific concerns. Transaction parameters are like EJB PROPAGATION_REQUIRED PROPAGATION_REQUIRED_NEW etc
JointPoint: A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.

What do you mean by Advice? and what are the Advices? Action taken by an aspect at a particular join point. Different types of advice include "around," "before" and "after" advice. Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors "around" the join point. Types of advice: Before advice: Advice that executes before a join point, but which does not have the ability to advice: prevent execution flow proceeding to the join point (unless it throws an exception). After returning advice: Advice to be executed after a join point completes normally: for advice: example, if a method returns without throwing an exception. After throwing advice: Advice to be executed if a method exits by throwing an exception. advice: After (finally) advice: Advice to be executed regardless of the means by which a join point advice: exits (normal or exceptional return). Around advice: Advice that surrounds a join point such as a method invocation. This is the advice: most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception

Spring Expression Language


Spring introduces an expression language which is similar to Unified EL in its syntax but offers significantly more features. The expression language can be used when defining XML and Annotation based bean definitions and also serves as the foundation for expression language support across the Spring portfolio. Details of this new functionality can be found in the chapter Spring Expression Language (SpEL).

Using your custom @qualifier

Life Cycle Annotaions

Pros Refactoring friendly Simplifies configuration Reduces redundancy Allows fine-grained control and customization Cons Changes require recompiling Only one bean instance per type Does not scale just by itself Tooling needed for larger projects

Should You Be Using Annotations? A consensus is beginning to emerge and it's not a resounding 'Yes! Ask yourself the following: does XML configuration work for me? are developers reasonably comfortable with XML? what tools are available? what is the size of my project and team? how static is my configuration?

Annotation vs. XML


Configuration Annotations can reduce configuration an important option to have! Tooling matters for both annotations lack global visibility XML is harder to manage without tools Annotations fall short in some cases wiring up 3rd party components multiple POJO instances Mixing and XML better for DSL matching works!

A Clear Winner For Integration Testing

También podría gustarte