Spring MVC

September 2007

Monday, June 06, 2011
© Kanbay Incorporated - All Rights Reserved

CONFIDENTIAL

Contents
»DispatcherServlet »Request flow in application »Meaning of Important terms »HandlerMapping  Commonly Used handlerMappings  Configuration  Registering more than one handlerMapping  Best Practices for designing handlerMapping »Interceptors  Purpose  Use cases  Example  Registering interceptor with URLHandlerMapping

Monday, June 06, 2011 | © Kanbay Incorporated. All Rights Reserved

CONFIDENTIAL

2

Contents continue »Controllers  Classification of spring controllers  SimpleFormController »Spring tag library  <spring-bind> tag  BindStatus object »ViewResolver »Spring I18n Monday. All Rights Reserved CONFIDENTIAL 3 . 2011 | © Kanbay Incorporated. June 06.

springframework.web. All Rights Reserved CONFIDENTIAL 4 .xml <servlet> <servlet-name>springWebMvcPract</servlet-name> <servlet-class> org. June 06. 2011 | © Kanbay Incorporated.DispatcherServlet It is Front controller for Spring web mvc Configuration in web.htm</url-pattern> </servlet-mapping> Monday.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>namespace</param-name> <param-value>XmlWebBeanFactory</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springWebMvcPract</servlet-name> <url-pattern>*.

All Rights Reserved CONFIDENTIAL 5 . 2011 | © Kanbay Incorporated.Request flow in application Monday. June 06.

Controller is basic controller available and all spring¶s controllers implements this interface ModelAndView Spring controller can return instance of ModelAndView Default Handler. All Rights Reserved CONFIDENTIAL 6 .springframework. June 06.servlet.Meaning of Important terms DispatherServlet first component which receive request is DispathcerServlet Handler Mapping Holds Mapping between URL and controller objects in application Default Handler Mapping is BeanNameUrlHandlerMapping Controller org. This object act as helper for DispatcherServlet in getting view Monday.web. 2011 | © Kanbay Incorporated.mvc.

JstlView Monday.view.servlet. June 06. All Rights Reserved CONFIDENTIAL 7 .View is basic interface available commonly used View implementation for JSP org. 2011 | © Kanbay Incorporated.web.springframework.servlet.Meaning of Important terms continue ViewResolver ViewResolver helps DispatcherServlet for getting instance of View that will render view Main Purpose of ViewResolver is to map logical view name with view Default ViewResolver for DispatcherServlet is InternalResourceViewResolver View This object is responsible for rendering view org.springframework.web.

Commonly Used HandlerMappings Commonly used HandlerMappings Name BeanNameUrlHandlerMapping Details Maps controller to URL based Imp note By default DispatcherServlet use this implementation on bean name SimpleUrlHandlerMapping Maps Controller to URL based on Property Monday. All Rights Reserved CONFIDENTIAL 8 . June 06. 2011 | © Kanbay Incorporated.HandlerMapping :.

All Rights Reserved CONFIDENTIAL 9 .com:8080/spring_mvc/s ecurity/login.Configuration For BeanNameUrlHandlerMapping When client send request to application as http://www.localhost.web.LoginController"> <property name="formView" value="login" /> <property name="successView" value="home" /> <property name="validator" ref="loginValidator" /> </bean> Monday.HandlerMapping :.htm" class="com.gp.htm Dispatcher servlet will dispatch request to LoginController Imp note Since BeanNameUrlHandlerMapping is default in spring application it is not necessary to define in XML bean factory When it is only URLHandlerMapper in application <bean name="/security/login.security. 2011 | © Kanbay Incorporated. June 06.co ntroller.common.

Configuration For SimpleUrlHandlerMapping This handler mapping maps URL to controller based on Property URL is act as a key while bean id act a Value Here /logout.htm">logoutController</prop> </props> </property> </bean> Controller definition <bean id="logoutController" class="com. value) URL HandlerMapping <bean id="restrictedUrlMapping" class="org.e.HandlerMapping :.common.springframework.handler.htm" /> </bean> Monday.Log outController"> <property name="logoutView" value="security/login.web. All Rights Reserved CONFIDENTIAL 10 . June 06.htm (i. 2011 | © Kanbay Incorporated.controller.servlet .security.web.gp.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/logout.e. Key) is mapped to bean with id logoutController (i.

June 06.springframework.HandlerMapping :.Registering More than one HandlerMapping Need For large applications which need modular division of code Here we defined 2 handler mappings With property order is initialized Value of order property priority <bean id="publicUrlMapping" class="org.servlet.web.springframework.BeanN ameUrlHandlerMapping"> <property name="order"> <value>0</value> </property> </bean> <bean id="restrictedUrlMapping" class="org. All Rights Reserved CONFIDENTIAL 11 .web.htm">logoutController</prop> </props> </property> here bean defined with id publicUrlMapping has highest priority <property name="order"> <value>1</value> </property> </bean> Monday.h andler.handler.servlet. 2011 | © Kanbay Incorporated.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/logout.

Best Practices 1] For large application divide application in small modules and for each module define one handler mapping if possible 2] Try to avoid using BeanNameUrlHanlderMappings since this scatters our URL mappings across multiple xml files 3] Define all handler mappings for whole application at one location Monday. 2011 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL 12 .HandlerMapping :. June 06.

Interceptors :.Purpose Spring Provides extremely useful functionality when we want to apply some specific functionalities to client requests Handler Interceptor process request before or after appropriate controller process request Monday. June 06. All Rights Reserved CONFIDENTIAL 13 . 2011 | © Kanbay Incorporated.

accessed Pages etc This information can be logged either in file or persisted in database 3] Increasing user experience This kind of use case can play important role when application moved to production mode and we need to check frequent visited pages by client Monday. his/her Locale. 2011 | © Kanbay Incorporated.g.. All Rights Reserved CONFIDENTIAL 14 .Interceptors :. login page. Client¶s IP address. June 06.g.g. Logout In this use case we need to check if user is having credentials to access this pages 2] We need to capture some important information related to client when client send request to server e.Use cases 1] Our URLs can be classified on Macro level in 2 parts Public URL e. forgot password page etc Restricted URL which need user¶s authentication e..

Example If you want to create your own interceptor you can choose to extend your class HandlerInterceptorAdapter or implement HandlerInterceptor When Interceptor handle request? It provides us functionality to process request before or after appropriate controller has processed it request.viewLocationForInvalidUrlAccess).Interceptors :.getSession(false).sendRedirect(request. } else { // user is having preExisting session then return true. All Rights Reserved CONFIDENTIAL 15 . if (session == null) { response. } } public boolean preHandle(HttpServletRequest request. Object handler) throws Exception { HttpSession session = Monday. return false. HttpServletResponse response. 2011 | © Kanbay Incorporated.getContextPat h() + "/" + this. June 06.

Interceptors :.BeanNameUrlHandlerMapping"> <property name="interceptors"> <list> <ref bean="localeChangeInterceptor" /> </list> </property> <property name="order"> <value>0</value> </property> </bean> Monday.servlet. 2011 | © Kanbay Incorporated.web.handler.Registering Interceptor with URLHandlerMapping <bean id="localeChangeInterceptor" class="org. June 06.servlet.springframework.i18n. All Rights Reserved CONFIDENTIAL 16 .LocaleChangeInterceptor"> </bean> <bean id="publicUrlMapping" class="org.web.springframework.

2011 | © Kanbay Incorporated.classification Monday. June 06.Controllers :. All Rights Reserved CONFIDENTIAL 17 .

class to be bind as a command object formView :. All Rights Reserved CONFIDENTIAL 18 . June 06.SimpleFormController When to use SimpleFormController When we need to process simple forms Mandatory attributes SimpleFormController commadClass :. 2011 | © Kanbay Incorporated.logical name of view after form submission validator :Features Provide Separation of Validation logic from controller Binding of value objects struts lacks in it Limitations Controller chaining is difficult or not possible to implement.logical name of form view Some other Imp attributes successView:. Struts Provide Action Chaining bean to validate form fields Monday.

in following listing we are accessing username attribute in comand object <spring: bind path="command. 2011 | © Kanbay Incorporated.getErrorMessage()%> </B> </FONT> </spring:bind> Monday. username"> <input type="text" name="userName" size="20" value="<%=status.Spring tag library <spring-bind> tag Purpose Used to access command object and error associated with command object Attributes It has only one attribute named path indicates bean or bean property being used e. June 06. All Rights Reserved CONFIDENTIAL 19 .getDisplayValue()%>"> <FONT color="red"> <B><%=status.g.

All Rights Reserved CONFIDENTIAL 20 .Spring tag library :. 2011 | © Kanbay Incorporated.BindStatus Object Spring provides org.BindStatus object available in page scope with name status Imp methods in BindStatus object available getDisplayValue() This method gives actual value of command attribute getErrorMessage() This method gives error associated with command attribute if any Monday.servlet.web.support. June 06.springframework.

servlet.web.url=/WEB-INF/viewshttps://www.scribd.com/jsp/common/login.springframework.properties from classpath --> <property name="basename" value="views" /> </bean> login.springframework.Log inController"> <property name="formView" value="login" /> <property name="successView" value="home" /> <property name="validator" ref="loginValidator" /> </bean> 21 .view.view. All Rights Reserved CONFIDENTIAL <bean name="/security/login. 2011 | © Kanbay Incorporated.ResourceBundleViewResolver First Listing shows bean definition For LoginController this is nothing but child of SimpleFormController While second listing shows definition of ViewResolver in XML bean factory When any client want to see Login page It will send request as http://localhost:8080/spring_mvc/security/login.web.htm" class="com.class=org.htm 3rd Listing shows definition View object and corresponding view location <bean id="viewResolver" class="org.this will going to fetch views.ViewResolver :.web. June 06.gp.security.servlet.controller.jsp Monday.J stlView login.common.Reso urceBundleViewResolver"> <!-.

CookieLocaleResolver" /> <bean id="localeChangeInterceptor" class="org. All Rights Reserved CONFIDENTIAL 22 .web.BeanNameUrlHandlerMapping"> <property name="interceptors"> <list> <ref bean="localeChangeInterceptor" /> </list> </property> </bean> Monday.servlet.Spring I18n Spring provides CookieLocaleResolver which allow user to change application language on the fly Configuration <bean id="localeResolver" class="org.i18n.springframework.springframework.servlet. 2011 | © Kanbay Incorporated.springframework.servlet.i18n.web. June 06.web.LocaleChangeInterceptor"> </bean> <bean id="publicUrlMapping" class="org.handler.

Reference »Pro Spring By Rob Harrop Apress publications »Spring In Action By Craig Walls Manning Publications Monday. 2011 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL 23 . June 06.

384.COM Monday.0500 WWW.All Rights Reserved CONFIDENTIAL .384. 2011 © Kanbay Incorporated .6100 Fax 847.KANBAY. ILLINOIS USA 60018 Tel. June 06.Kanbay WORLDWIDE HEADQUARTERS 6400 SHAFER COURT ROSEMONT. 847.