You are on page 1of 24

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

2011 | © Kanbay Incorporated.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 . June 06.

web.springframework. 2011 | © Kanbay Incorporated.xml <servlet> <servlet-name>springWebMvcPract</servlet-name> <servlet-class> org. June 06.htm</url-pattern> </servlet-mapping> Monday. All Rights Reserved CONFIDENTIAL 4 .DispatcherServlet It is Front controller for Spring web mvc Configuration in web.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>*.

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

springframework. June 06.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.Controller is basic controller available and all spring¶s controllers implements this interface ModelAndView Spring controller can return instance of ModelAndView Default Handler.web. All Rights Reserved CONFIDENTIAL 6 . This object act as helper for DispatcherServlet in getting view Monday.servlet. 2011 | © Kanbay Incorporated.mvc.

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. All Rights Reserved CONFIDENTIAL 7 . 2011 | © Kanbay Incorporated. June 06.View is basic interface available commonly used View implementation for JSP org.web.JstlView Monday.servlet.servlet.springframework.springframework.view.web.

2011 | © Kanbay Incorporated. June 06. All Rights Reserved CONFIDENTIAL 8 .HandlerMapping :.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 9 .HandlerMapping :.co ntroller.security.com:8080/spring_mvc/s ecurity/login. 2011 | © Kanbay Incorporated.localhost.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.Configuration For BeanNameUrlHandlerMapping When client send request to application as http://www.htm" class="com.gp. June 06.web.common.LoginController"> <property name="formView" value="login" /> <property name="successView" value="home" /> <property name="validator" ref="loginValidator" /> </bean> Monday.

controller.security.htm">logoutController</prop> </props> </property> </bean> Controller definition <bean id="logoutController" class="com. value) URL HandlerMapping <bean id="restrictedUrlMapping" class="org.htm (i.HandlerMapping :.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. June 06.e.e. All Rights Reserved CONFIDENTIAL 10 .springframework.servlet .htm" /> </bean> Monday.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/logout.web.web.handler. 2011 | © Kanbay Incorporated.gp. Key) is mapped to bean with id logoutController (i.Log outController"> <property name="logoutView" value="security/login.

springframework.htm">logoutController</prop> </props> </property> here bean defined with id publicUrlMapping has highest priority <property name="order"> <value>1</value> </property> </bean> Monday. All Rights Reserved CONFIDENTIAL 11 .web.HandlerMapping :. 2011 | © Kanbay Incorporated.handler.BeanN ameUrlHandlerMapping"> <property name="order"> <value>0</value> </property> </bean> <bean id="restrictedUrlMapping" class="org.springframework.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/logout. June 06.web.h andler.servlet.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.

HandlerMapping :. All Rights Reserved CONFIDENTIAL 12 . 2011 | © Kanbay Incorporated. June 06.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.

Interceptors :. All Rights Reserved CONFIDENTIAL 13 . June 06. 2011 | © Kanbay Incorporated.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.

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.g.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. Client¶s IP address.Interceptors :. forgot password page etc Restricted URL which need user¶s authentication e.. June 06.Use cases 1] Our URLs can be classified on Macro level in 2 parts Public URL e. login page.. his/her Locale. All Rights Reserved CONFIDENTIAL 14 . 2011 | © Kanbay Incorporated.

} } public boolean preHandle(HttpServletRequest request. } else { // user is having preExisting session then return true.Interceptors :. June 06. All Rights Reserved CONFIDENTIAL 15 .sendRedirect(request. 2011 | © Kanbay Incorporated. if (session == null) { response.getSession(false).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. HttpServletResponse response. return false.viewLocationForInvalidUrlAccess).getContextPat h() + "/" + this. Object handler) throws Exception { HttpSession session = Monday.

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

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

All Rights Reserved CONFIDENTIAL 18 . Struts Provide Action Chaining bean to validate form fields Monday. 2011 | © Kanbay Incorporated.logical name of form view Some other Imp attributes successView:. June 06.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.class to be bind as a command object formView :.SimpleFormController When to use SimpleFormController When we need to process simple forms Mandatory attributes SimpleFormController commadClass :.

g. in following listing we are accessing username attribute in comand object <spring: bind path="command.getDisplayValue()%>"> <FONT color="red"> <B><%=status. username"> <input type="text" name="userName" size="20" value="<%=status.getErrorMessage()%> </B> </FONT> </spring:bind> Monday. All Rights Reserved CONFIDENTIAL 19 . 2011 | © Kanbay Incorporated.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.

BindStatus Object Spring provides org.springframework. 2011 | © Kanbay Incorporated. June 06.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.support.Spring tag library :.servlet. All Rights Reserved CONFIDENTIAL 20 .web.

htm" class="com. June 06.J stlView login.url=/WEB-INF/viewshttps://www.scribd.com/jsp/common/login.web.web.ViewResolver :.common.gp.servlet.view. All Rights Reserved CONFIDENTIAL <bean name="/security/login.Log inController"> <property name="formView" value="login" /> <property name="successView" value="home" /> <property name="validator" ref="loginValidator" /> </bean> 21 .jsp Monday.servlet.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.view.class=org.springframework.security.web.springframework.controller.this will going to fetch views.Reso urceBundleViewResolver"> <!-.htm 3rd Listing shows definition View object and corresponding view location <bean id="viewResolver" class="org. 2011 | © Kanbay Incorporated.properties from classpath --> <property name="basename" value="views" /> </bean> login.

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

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

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