Spring Mvc

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

1 comments

Comments 1 - 1 of 1 previous next Post a comment

Post a comment
Embed Video
Edit your comment Cancel

4 Favorites

Spring Mvc - Presentation Transcript

  1. Developing Web Applications with Spring MVC Ryan Breidenbach Countrywide Financial Corporation
  2. Token “Who Am I?” slide
    • Developing JEE applications for the past 7 years
    • Developing Spring applications for over 3 years
    • Coauthor of Spring in Action
    • Currently developing applications for Countrywide Financial Corporation
  3. Agenda
    • Introduction to Spring MVC
    • Overview of architecture
    • Overview and examples of individual MVC components
    • In depth examples of forms processing and validation
    • Miscellaneous topics
    • Questions
  4. What is Spring MVC?
    • Request-response based web application framework, such as Struts and WebWork
    • Flexible and extensible via component’s interfaces
    • Simplifies testing through Dependency Injection
    • Simplifies form handling through its parameter binding, validation and error handling
    • Abstracts view technology (JSP, Velocity, FreeMarker Excel , PDF)
  5. Spring MVC Architecture
  6. DispatcherServlet
  7. DispatcherServlet
    • Example of Front Controller pattern - entry point for all Spring MVC requests
    • Loads WebApplicationContext and well are parent contexts
    • Controls workflow and mediates between MVC components
    • Loads sensible default components if none are configured
  8. Configuring the DispatcherServlet
    • web.xml
    • <servlet>
    • <servlet-name>dispatcher</servlet-name>
    • <servlet-class>
    • org.springframework.web.servlet.DispatcherServlet
    • </servlet-class>
    • <load-on-startup>1</load-on-startup>
    • </servlet>
    • <servlet-mapping>
    • <servlet-name>dispatcher</servlet-name>
    • <url-pattern>*.htm</url-pattern>
    • </servlet-mapping>
  9. Configuring the DispatcherServlet (cont’d)
    • web.xml
    • <servlet>
    • <servlet-name>dispatcher</servlet-name>
    • <servlet-class>
    • org.springframework.web.servlet.DispatcherServlet
    • </servlet-class>
    • <init-param>
    • <param-name>contextConfigLocation</param-name>
    • <param-value>WEB-INF/mvc.xml</param-value>
    • </init-param>
    • <load-on-startup>1</load-on-startup>
    • </servlet>
  10. Configuring the DispatcherServlet (cont’d)
    • web.xml
    • <context-param>
    • <param-name>contextConfigLocation</param-name>
    • <param-value>/WEB-INF/services.xml</param-value>
    • </context-param>
    • <listener>
    • <listener-class>
    • org.springframework.web.context.ContextLoaderListener
    • </listener-class>
    • </listener>
    configures parent context
  11. HandlerMapping
  12. HandlerMapping
    • Maps incoming requests to a corresponding Handler, typically a Controller
    • Rarely needs to be implemented directly – many useful implementations are provided
    • Also ties Interceptors to a mapped Controllers
    • Can provided multiple HandlerMappings; priority is set using Ordered interface
  13. BeanNameUrlHandlerMapping
    • Maps a URL to a bean registered with the same name – e.g. /simple.htm maps to a bean named “/simple.htm”
    • Can give bean multiple names (aliases) separated by spaces
    • Must use name attribute – “/” is not allowed in XML id attribute
    • Can use wild card in bean names (/simple*)
    • Default HandlerMapping , but not preferred
  14. BeanNameUrlHandlerMapping
    • dispatcher-servlet.xml
    • <bean class=&quot;org.springframework.web.servlet.
    • handler.BeanNameUrlHandlerMapping&quot;/>
    • <bean name=&quot;/simple.htm /simpleSimon.htm&quot;
    • class=&quot;com.twoqubed.mvc.web.SimpleController&quot;>
    • </bean>
  15. SimpleUrlHandlerMapping
    • Most common way to map request URLs to handlers
    • Configured by a list of name/value pairs consisting of URLs and bean names
    • Can use wild card in bean names (/simple*)
  16. SimpleUrlHandlerMapping
    • dispatcher-servlet.xml
    • <bean class=&quot;org.springframework.web.servlet.
    • handler.SimpleUrlHandlerMapping&quot;>
    • <property name=&quot;mappings&quot;>
    • <value>
    • /simple.htm=simpleController
    • /test*=testController
    • </value>
    • </property>
    • </bean>
  17. ControllerClassNameHandlerMapping
    • Part of Spring 2.0's Convention over Configuration
    • Maps a URL to the shortened class name of a Controller bean
      • Removed &quot;Controller&quot; from class name
      • Converts to all lower case
      • Prepend and &quot;/&quot; and append a &quot;*&quot;
    • Example:
      • SimpleController -> /simple*
    • Greatly reduces amount of mapping configurations
  18. ControllerClassNameHandlerMapping
    • dispatcher-servlet.xml
    • <bean class=&quot;org.springframework.web.servlet.mvc.
    • support.ControllerClassNameHandlerMapping&quot; />
  19. Controllers
  20. Controller interface
    • Handles the processing of the request
    • Interface parameters mimics HttpServlet
      • handleRequest(HttpServletRequest, HttpServletResponse)
    • Returns a ModelAndView object
    • Implementations are typically thread-safe
    • Rarely implemented directly – Spring provides many useful implementations
  21. ModelAndView object
    • Encapsulates both model and view that is to be used to render model
    • Model is represented as a java.util.Map
    • Objects can be added to without name:
      • addObject(String, Object) – added with explicit name
      • addObject(Object) – added using name generation ( Convention over Configuration )
    • View is represented by String or View object
    • Analogous to Struts Action
  22. Controller implementations
    • Typical Controllers in your application will:
      • Be completely configured via wiring (no code)
      • Contain simple web processing
      • Handle web layer and defer to service layer for additional processing
        • Parameter handling
        • View determination
        • Input validation
  23. AbstractController
    • Provides minimal behavior
    • Used for handling simple requests
    • protected ModelAndView handleRequestInternal(
    • HttpServletRequest request,
    • HttpServletResponse response) {
    • String text = service.getText();
    • return new ModelAndView(
    • &quot;simple&quot;, &quot;text&quot;, text);
    • }
  24. AbstractController
    • Provides minimal behavior
    • Used for handling simple requests
    • protected ModelAndView handleRequestInternal(
    • HttpServletRequest request,
    • HttpServletResponse response) {
    • String text = service.getText();
    • return new ModelAndView(
    • &quot;simple&quot;, &quot;text&quot;, text);
    • }
  25. ThrowawayController
    • Not part of the Controller hierarchy
    • Parameters are mapped directly onto the controller
    • Useful when there is not model object to map to
    • Must scope bean as prototype since these are inherently not thread-safe
  26. ThrowawayController
    • dispatcher-servlet.xml
    • <bean id=&quot;exampleThrowawayController&quot;
    • class=&quot;com.twoqubed.mvc.web.
    • ExampleThrowawayController&quot;
    • scope=&quot;prototype&quot; />
    configured as prototype bean
  27. ThrowawayController
    • public class ExampleThrowawayController
    • implements ThrowawayController {
    • private String message;
    • public void setMessage(String message) {
    • this.message = message;
    • }
    • public ModelAndView execute() throws Exception {
    • String hashCodeMessage = &quot;[&quot; + hashCode()
    • + &quot;] - &quot; + message;
    • return new ModelAndView(&quot;throwaway&quot;, &quot;message&quot;,
    • hashCodeMessage);
    • }
    • }
  28. Command Controllers
    • Family of Controllers that bind request parameters to command objects
    • Command object can be any POJO – typically a domain object
    • Provides functionality:
      • Binding custom types
      • Automatic and custom validation
      • Automatically or programmatically creating command object
    • We will cover in more detail later…
  29. Command Controllers
    • AbstractCommandController – Provides binding and validation
    • SimpleFormController – In addition to binding and validation, provides rich work flow for processing forms
      • Most useful for processing form
      • Detailed example to come later
    • AbstractWizardFormController – For forms that span multiple pages
  30. Additional Controllers
    • ServletWrappingController and ServletForwardingController – specialty Controllers to wrap Struts servlet in Spring interceptors
    • ParameterizableViewController – simply forwards to a configured view without exposing view technology to client
    • UrlFilenameViewController – converts a URL to a view name
  31. Interceptors
  32. Interceptors
    • Add additional functionality before and after request
    • Contains to interception methods – preHandle and postHandle
    • Contains one callback method – afterCompletetion
    • Associated with a set of Controllers via a HandlerMapping
  33. Interceptor implementations
    • Implement either HandlerInterceptor or WebRequestInterceptor
    • Spring provides a few implementations
      • OvenXxxInViewInteceptor – Used with ORM frameworks JDO, JPA and Hibernate
      • UserRoleAuthorizationInterceptor – Provides authorization against a set of roles
    • Other useful customizations: custom security, caching, …
  34. ViewResolver
  35. ViewResolver
    • Resolves a logical view name to a View object
    • Orderable, so they be chained
    • For JSP user, typical implementation is InternalResourceViewResolver:
    • <bean id=&quot;internalResourceViewResolver&quot; …
    • <property name=&quot;prefix&quot; value=&quot;/WEB-INF/jsp/&quot; />
    • <property name=&quot;suffix&quot; value=&quot;.jsp&quot; />
    • </bean>
  36. Other ViewResolver Implementations
    • VelocityViewResolver – Convenience class for Velocity templates
    • FreeMarkerViewResolver – Convenience class for FreeMarker templates
    • ResourceBundleViewResolver
      • Mappings are contained within a properties file
      • Supports internationalization
    • XmlViewResolver - Mappings are contained with an XML file
  37. View
  38. View
    • Contains implementations for several template technologies:
      • InternalResourceView (JSP)
      • JstlView (JSP + JSTL)
      • VelocityView (Velocity)
      • FreeMarkerView (FreeMarker)
      • TilesView (Tiles)
      • TilesJstlView (Tiles + JSTL)
  39. View
    • Also contains views that support rendering
      • Excel files
      • PDF files
      • XSLT results
      • Jasper Reports
  40. Processing forms with Spring MVC
    • Leveraging workflow provided by SimpleFormController
      • Provides both form display and processing work flow with custom hooks
      • Be default, GET indicates form displaying and POST indicates form processing
    • Displaying and processing done by same Controller
    • Complete workflow is quite involved – we will only hit the highlights
  41. Registering the Command class
    • SimpleFormControllers are associated with a Command class
      • Since these are tightly coupled, configuring with the Controller class is acceptable
    • public class PlayerFormController
    • extends SimpleFormController {
    • public PlayerFormController() {
    • setCommandClass(Player.class);
    • setCommandName(&quot;player&quot;);
    • }
  42. Displaying a form
    • We will discuss three methods in the work flow for displaying the form
      • formBackingObject – Returns the command object used in the form.
      • initBinder – Registered custom PropertyEditors for rendering command properties
      • referenceData – Loads additional data to be displayed on page
  43. Processing a form
    • Two main methods for form processing are:
      • onBindAndValidate() – Allows for custom binding and validation
      • doSubmitAction() – Callback to handle successful form submission. Typical implementation would be to persist command object to database.
  44. Spring MVC Grab Bad
    • Other Spring MVC functionality not covered (but is cool nonetheless)
      • Transparent handling of Multipart requests
      • Support for customized Look & Feels through Themes
      • Support for internalization
      • Convenience ServletContextListener for initializing Log4J
  45. Questions
    • Resources
      • Presentation and code
        • http://www.twoqubed.com/svn/presentations/tags
      • Spring Framework forms
        • http://forum.springframework.org
      • Spring MVC Official Documentation
        • http://static.springframework.org/spring/docs/2.0.x/reference/mvc.html
      • Spring Tag Library Official Documentation
        • http://static.springframework.org/spring/docs/2.0.x/reference/spring-form.tld.html

+ Srinu MSrinu M, 2 years ago

custom

3623 views, 4 favs, 0 embeds more stats

More info about this document

© All Rights Reserved

Go to text version

  • Total Views 3623
    • 3623 on SlideShare
    • 0 from embeds
  • Comments 1
  • Favorites 4
  • Downloads 0
Most viewed embeds

more

All embeds

less

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

Cancel
File a copyright complaint
Having problems? Go to our helpdesk?

Categories