Spring MVC
-
Upload
api-3776282 -
Category
Documents
-
view
7 -
download
1
description
Transcript of Spring MVC
Saturday, April 8, 2023 CONFIDENTIAL
© Kanbay Incorporated - All Rights Reserved
Spring MVC September 2007
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL2
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
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL3
Contents continue
»Controllers Classification of spring controllers SimpleFormController
»Spring tag library <spring-bind> tag BindStatus object
»ViewResolver»Spring I18n
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL4
DispatcherServlet It is Front controller for Spring web mvcConfiguration in web.xml
<servlet>
<servlet-name>springWebMvcPract</servlet-name>
<servlet-class>
org.springframework.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>*.htm</url-pattern> </servlet-mapping>
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL5
Request flow in application
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL6
Meaning of Important terms
DispatherServletfirst component which receive request is DispathcerServlet
Handler MappingHolds Mapping between URL and controller objects in application
Default Handler Mapping is BeanNameUrlHandlerMapping
Controller org.springframework.web.servlet.mvc.Controller is basic controller available and all spring’s controllers implements this interface
ModelAndViewSpring controller can return instance of ModelAndView Default Handler.
This object act as helper for DispatcherServlet in getting view
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL7
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
ViewThis object is responsible for rendering view
org.springframework.web.servlet.View is basic interface available
commonly used View implementation for JSP
org.springframework.web.servlet.view.JstlView
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL8
HandlerMapping :- Commonly Used HandlerMappings
Commonly used HandlerMappings
Name Details Imp noteBeanNameUrlHandlerMapping Maps controller to URL based
on bean nameBy default DispatcherServlet use this implementation
SimpleUrlHandlerMapping Maps Controller to URL based on Property
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL9
HandlerMapping :- Configuration
For BeanNameUrlHandlerMapping
When client send request to application as
http://www.localhost.com:8080/spring_mvc/security/login.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.htm"class="com.gp.common.security.web.controller.LoginController">
<property name="formView" value="login" />
<property name="successView" value="home" />
<property name="validator" ref="loginValidator" />
</bean>
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL10
HandlerMapping :- ConfigurationFor SimpleUrlHandlerMapping
This handler mapping maps URL to controller based on Property
URL is act as a key while bean id act aValue
Here /logout.htm (i.e. Key) is mapped to bean with id logoutController (i.e. value)
URL HandlerMapping
<bean id="restrictedUrlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings"> <props>
<prop key="/logout.htm">logoutController</prop>
</props></property></bean>
Controller definition<bean id="logoutController"class="com.gp.common.security.web.controller.LogoutController">
<property name="logoutView" value="security/login.htm" />
</bean>
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL11
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 ↑
here bean defined with id publicUrlMapping has highest priority
<bean id="publicUrlMapping"class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"><property name="order"><value>0</value></property></bean>
<bean id="restrictedUrlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/logout.htm">logoutController</prop>
</props>
</property>
<property name="order"><value>1</value></property></bean>
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL12
HandlerMapping :- 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
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL13
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
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL14
Interceptors :- Use cases
1] Our URLs can be classified on Macro level in 2 parts Public URL e.g. login page, forgot password page etcRestricted URL which need user’s authentication e.g.. LogoutIn 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.g.. Client’s IP address, his/her Locale, accessed Pages etcThis information can be logged either in file or persisted in database3] 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
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL15
Interceptors :- 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
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession(false);
if (session == null) {
response.sendRedirect(request.getContextPath() + "/"
+ this.viewLocationForInvalidUrlAccess);
return false;
} else {
// user is having preExisting session then
return true;
}
}
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL16
Interceptors :- Registering Interceptor with URLHandlerMapping
<bean id="localeChangeInterceptor"class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
</bean>
<bean id="publicUrlMapping"
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<property name="interceptors"><list><ref bean="localeChangeInterceptor" /></list></property><property name="order">
<value>0</value>
</property>
</bean>
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL17
Controllers :- classification
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL18
SimpleFormControllerWhen to use SimpleFormControllerWhen we need to process simple forms
Mandatory attributes SimpleFormController commadClass :- class to be bind as a command objectformView :- logical name of form view
Some other Imp attributessuccessView:- logical name of view after form submissionvalidator :- bean to validate form fields
FeaturesProvide Separation of Validation logic from controllerBinding of value objects struts lacks in it
LimitationsController chaining is difficult or not possible to implement.Struts Provide Action Chaining
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL19
Spring tag library <spring-bind> tag
PurposeUsed 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.g. in following listing we are accessing username attribute in comand object
<spring: bind path="command. username"><input type="text" name="userName" size="20"
value="<%=status.getDisplayValue()%>">
<FONT color="red"> <B><%=status.getErrorMessage()%>
</B> </FONT>
</spring:bind>
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL20
Spring tag library :- BindStatus Object
Spring provides
org.springframework.web.servlet.support.BindStatusobject available in page scope with name status
Imp methods in BindStatus object availablegetDisplayValue()
This method gives actual value of command attribute
getErrorMessage()
This method gives error associated with command attribute if any
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL21
ViewResolver :- ResourceBundleViewResolver
<bean name="/security/login.htm"
class="com.gp.common.security.web.controller.LoginController">
<property name="formView" value="login" /><property name="successView" value="home" /><property name="validator" ref="loginValidator" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<!-- this will going to fetch views.properties from classpath -->
<property name="basename" value="views" />
</bean>
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.htm
3rd Listing shows definition View object and corresponding view location
login.class=org.springframework.web.servlet.view.JstlView
login.url=/WEB-INF/views/jsp/common/login.jsp
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL22
Spring I18n
Spring provides CookieLocaleResolver which allow user to change application language on the fly
Configuration
<bean id="localeResolver"class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
</bean>
<bean id="publicUrlMapping"
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<property name="interceptors"><list><ref bean="localeChangeInterceptor" /></list></property></bean>
Saturday, April 8, 2023 | © Kanbay Incorporated. All Rights Reserved CONFIDENTIAL23
Reference
»Pro Spring By Rob Harrop Apress publications
»Spring In Action
By Craig Walls
Manning Publications
Saturday, April 8, 2023 CONFIDENTIAL
© Kanbay Incorporated - All Rights Reserved
KanbayWORLDWIDE HEADQUARTERS 6400 SHAFER COURT ROSEMONT, ILLINOIS USA 60018
Tel. 847.384.6100 Fax 847.384.0500 WWW.KANBAY.COM