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.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    5 Favorites, 1 Group & 1 Event

    Spring MVC - Presentation Transcript

    1.  
    2. Spring MVC Dror Bereznitsky Senior Consultant and Architect, AlphaCSP It’s Time
    3. Agenda
      • Introduction
      • Background
      • Features Review
        • Configuration
        • View technology
        • Page flow
        • Table sorting
        • Search results pagination
        • Validation
        • AJAX
        • Error handling
        • I18n
        • Documentation
      • Summary
    4. Introduction
      • Spring’s web framework
        • Optional Spring framework component
        • Integrated with the Spring IoC container
      • Web MVC framework
        • Request-driven action framework
        • Designed around a central servlet
        • Easy for Struts users to adopt
    5. Introduction:: Key Features
      • Simple model
        • Easy to get going - fast learning curve
      • Designed for extension
        • Smart extension points put you in control
      • Strong integration
        • Integrates popular view technologies
      • A part of the Spring framework
        • All artifacts are testable and benefit from dependency injection
    6. Introduction:: More Key Features
      • Strong REST foundations
      • Data Binding Framework
      • Validation Framework
      • Internationalization Support
      • Tag Library
    7. Introduction:: Full Stack Framework?
      • Spring MVC is not a full-stack web framework, but provide the foundations for such
      • Spring MVC is not opinionated
        • You use the pieces you need
        • You adopt the pieces in piece-meal fashion
    8. Introduction:: Spring 2.5
      • Released November 2007
      • Simplified, annotation based model for developing Spring MVC applications
      • Less XML than previous versions
      • Focuses on
        • ease of use
        • smart defaults
        • simplified programming model
    9. Agenda
      • Introduction
      • Background
      • Features Review
        • Configuration
        • View technology
        • Page flow
        • Table sorting
        • Search results pagination
        • Validation
        • AJAX
        • Error handling
        • I18n
        • Documentation
      • Summary
    10. Background:: Dispatcher Servlet
      • Dispatcher Servlet - front controller that coordinates the processing of all requests
        • Dispatches requests to handlers
        • Issues appropriate responses to clients
      • Analogous to a Struts Action Servlet
      • Define one per logical web application
    11. Background:: Request Handlers
      • Incoming requests are dispatched to handlers
        • There are potentially many handlers per Dispatcher Servlet
        • Controllers are request handlers
    12. Background:: ModelAndView
      • Controllers return a result object called a ModelAndView
        • Selects the view to render the response
        • Contains the data needed for rendering
      • Model = contract between the Controller and the View
      • The same Controller often returns different ModelAndView objects
        • To render different types of responses
    13. Background:: Request Lifecycle Copyright 2006, www.springframework.org Handler
    14. Features Review
      • Introduction
      • Background
      • Features Review
        • Configuration
        • View technology
        • Page flow
        • Table sorting
        • Search results pagination
        • Validation
        • AJAX
        • Error handling
        • I18n
        • Documentation
      • Summary
    15. Features:: Configuration
      • Old school Spring beans XML configuration
      • Annotation based configuration for Controllers (v2.5)
        • XML configuration is still required for more advanced features: interceptors, view resolver, etc.
        • Not mandatory, everything can still be done with XML
    16. Deploy a DispatcherServlet
      • Minimal web deployment descriptor
      web.xml <servlet> <servlet-name> spring-mvc-demo </servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name> contextConfigLocation </param-name> <param-value> /WEB-INF/spring-mvc-demo-servlet.xml </param-value> </init-param> </servlet> Dispatcher servlet configuration
    17. Annotated Controllers
      • Simple POJO – no need to extend any controller base class !
      @Controller public class PhoneBookController { @RequestMapping ( value = &quot;/phoneBook&quot; , method = RequestMethod. GET ) protected ModelAndView setupForm() throws Exception { ModelAndView mv = new ModelAndView(); … return mv; } PhoneBookController.java
    18. Dispatcher Servlet Configuration
      • /WEB-INF/spring-mvc-demo.xml
        • Setting up the dispatcher for annotation support
        • Actually done by default for DispatcherServlet
        • Auto detection for @Controller annotated beans
      <bean class= &quot;org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping&quot; /> <bean class= &quot;org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter&quot; /> <context:component-scan base-package= &quot;com.alphacsp.webFrameworksPlayoff &quot; />
      • Supported out of the box:
        • JSP / JSTL
        • XML / XSLT
        • Apache Velocity
        • Freemarker
        • Adobe PDF
        • Microsoft Excel
        • Jasper Reports
      Features:: View Technology
    19. Configure the view technology
      • View Resolvers
        • Renders the model
        • Decoupling the view technology
      • JSTL view
        • JSP + JSTL –native choice for Spring MVC
        • Spring tag libraries
      <bean class = &quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot; > <property name = &quot;viewClass&quot; value = &quot;org.springframework.web.servlet.view. JstlView “ /> <property name = &quot;prefix&quot; value = &quot;/WEB-INF/views&quot; /> <property name = &quot;suffix&quot; value = &quot; . jsp&quot; /> </bean>
    20. Features:: Page Flow mv.setView( new RedirectView( &quot;../phoneBook“ , true ));
    21. Features:: Page Flow – Step 1
      • Mapping URLs to handler methods
        • Method level annotations
        • Can restrict to specific request method
        • URL strings can be error prone !
      @RequestMapping ( value = &quot;/phoneBook&quot; , method = RequestMethod. GET ) protected ModelAndView setupForm() throws Exception { ModelAndView mv = new ModelAndView(); mv.addObject( &quot;contacts&quot; , Collections.<Contact>emptyList()); mv.addObject( &quot;contact&quot; , new Contact()); … } PhoneBookController.java
    22. Page Flow – Step 1 Contd. DispatcherServlet PhoneBookController Handle GET /demo/phoneBook 1 InternalResource ViewResolver 2 phoneBook /WEB-INF/views/phoneBook.jsp phoneBook
    23. Page Flow – Step 2
      • Choosing the view to be rendered
        • Set the ModelAndView view name
        • Or just return a view name String
      PhoneBookController.java
      • @RequestMapping ( value = &quot;/phoneBook&quot; , method = RequestMethod. GET )
      • protected ModelAndView setupForm() throws Exception {
        • ModelAndView mv = new ModelAndView();
        • mv.setViewName( &quot;phoneBook&quot; );
        • return mv;
      @RequestMapping ( value = &quot;/phoneBook&quot; , method = RequestMethod. GET ) protected ModelAndView setupForm() throws Exception { return &quot; phoneBook &quot; ; }
    24. Page Flow – Step 2 Contd. DispatcherServlet PhoneBookController Handle GET /demo/phoneBook 1 InternalResource ViewResolver 2 phoneBook /WEB-INF/views/phoneBook.jsp phoneBook
    25. Features:: Sorting & Pagination Search results pagination Sorting by column
    26. Features:: Table Sorting
      • Used the display tag library
        • Handles column display, sorting, paging, cropping, grouping, exporting, and more
        • Supports internal and external sorting
        • Sort only visible records or the entire list
      <%@ taglib uri = &quot; http://displaytag.sf.net &quot; prefix = &quot; display &quot; %> <display:table name = &quot;contacts&quot; class = &quot;grid&quot; id = &quot;contacts&quot; sort = &quot;list&quot; pagesize = &quot;5&quot; requestURI = &quot;/demo/phoneBook/list&quot; > <display:column property =&quot; fullName&quot; title = &quot;Name&quot; class = &quot;grid&quot; headerClass = &quot;grid&quot; sortable = &quot;true&quot; /> … </display:table> phoneBook.jsp
    27. Features:: Search Results Pagination
      • Used the display tag pagination support for the demo
        • Supports internal and external pagination
        • Adds pagination parameter to request
        • Limited to HTTP GET
    28. Features:: Form Binding
      • @ModelAttribute annotations
      • Spring’s form tag library
        • EL expressions for binding path
      <td class = &quot;searchLabel&quot; ><b><label for = &quot;email&quot; > Email </label></b></td> <td class = &quot;search&quot; > <form:input id = &quot;email“ path = &quot;email&quot; tabindex = &quot;2&quot; /> </td> @RequestMapping ( value = &quot;/phoneBook/list&quot; ) protected ModelAndView onSubmit( @ModelAttribute ( &quot;contact&quot; ) Contact contact, BindingResult result)
    29. Features:: Validations
      • Used Spring Modules bean validation framework for server side validation
        • Clear separation of concerns
        • Declarative validation as in commons-validation
        • Supports Valang - extensible expression language for validation rules
    30. Bean Validation Configuration
      • Load validation XML configuration file [1]
      • Create a bean validator [2]
      <bean id = &quot;configurationLoader&quot; class = &quot;DefaultXmlBeanValidationConfigurationLoader&quot; > <property name = &quot;resource&quot; value = &quot;WEB-INF/validation.xml&quot; /> </bean> <bean id = &quot;beanValidator&quot; class = &quot;org.springmodules.validation.bean.BeanValidator&quot; > <property name = &quot;configurationLoader&quot; ref = &quot;configurationLoader&quot; /> </bean> 1 2
    31. Bean Validation Configuration
      • Contact email validation
        • Bound to the domain model and not to a specific form
      Validation.xml <validation> <class name = &quot;com.alphacsp.webFrameworksPlayoff . Contact &quot; > <property name = &quot;email&quot; > <email message = &quot;Please enter a valid email address&quot; apply-if = &quot;email IS NOT BLANK&quot; /> </property> </class> </validation> Domain Model
    32. Server Side Validations
      • Validator is injected to the controller
      • Reusing the binding errors object
      PhoneBookController.java @Autowired Validator validator; @RequestMapping ( value = &quot;/phoneBook/list&quot; ) protected ModelAndView onSubmit( @ModelAttribute ( &quot;contact&quot; ) Contact contact, BindingResult result) throws Exception { … validator.validate(contact, result); …
    33. Client Side Validation
      • Valang validator
        • validation is defined in valang expression language
      <bean id = &quot;clientSideValidator&quot; class = &quot;org.springmodules.validation.valang.ValangValidator&quot; > <property name = &quot;valang&quot; > <value> <![CDATA[ { firstName : ? IS NOT BLANK OR department IS NOT BLANK OR email IS NOT BLANK : 'At least one field is required'} ]]> </value> </property> </bean>
    34. Client Side Validation Contd.
      • Use Valang tag library to apply the valang validator at client side
        • Validation expression is translated to JavaScript
      <script type = &quot;text/javascript&quot; id = &quot;contactValangValidator&quot; > new ValangValidator( 'contact' , true,new Array( new ValangValidator.Rule(' firstName' , 'not implemented' , 'At least one field is required' , function () { return ((! this.isBlank((this.getPropertyValue( 'firstName' )), ( null ))) || (! this.isBlank((this.getPropertyValue( 'department' )), ( null )))) || (! this.isBlank((this.getPropertyValue( 'email' )), ( null )))}))) </script> phoneBook.jsp <%@ taglib uri = &quot;http://www.springmodules.org/tags/valang&quot; prefix = &quot;valang&quot; %> <script type = &quot;text/javascript&quot; src = &quot;/scripts/valang_codebase.js&quot; ></script> <form:form method = &quot;POST&quot; action = &quot;/demo/phoneBook/list&quot; id = &quot;contact&quot; name = &quot;contact&quot; commandName = &quot;contact&quot; > <valang:validate commandName = &quot;contact&quot; />
    35. Features:: AJAX
      • No built in AJAX support
        • DWR is unofficially recommended by Spring
      • Used DWR to expose the department service to JavaScript
        • Requires dealing for low-level AJAX
        • DWR has simple integration with Spring
      • Used script.aculo.us autocomplete component with DWR
    36. AJAX:: Configuration
      • The department service Spring bean
      <dwr> <allow> <create creator = &quot;spring&quot; javascript = &quot;DepartmentServiceFacade&quot; > <param name = &quot;beanName&quot; value = &quot;departmentServiceFacade&quot; /> </create> </allow> </dwr> <bean id =&quot;departmentServiceFacade&quot; class = &quot;com.alphacsp.webFrameworksPlayoff.service.impl. MockRemoteDepartmentServiceImpl“ />
      • Exposing it to JavaScript using DWR
      DWR.xml
    37. AJAX:: Autocomplete Component <script type = &quot;text/javascript&quot; src = &quot;/scripts/prototype/prototype.js&quot; ></script> <script type = &quot;text/javascript&quot; src = &quot;/scripts/script.aculo.us/controls.js&quot; ></script> <script type = &quot;text/javascript&quot; src = &quot;/scripts/autocomplete.js&quot; ></script> <td class=&quot;search&quot;> <form:input id = &quot;department&quot; path = &quot;department&quot; tabindex = &quot;3&quot; cssClass = &quot;searchField&quot; /> <div id = &quot;departmentList&quot; class = &quot;auto_complete&quot; ></div> <script type = &quot;text/javascript&quot; > new Autocompleter.DWR( 'department' , 'departmentList' , updateList, {valueSelector: nameValueSelector, partialChars: 0 }); </script> </td> phoneBook.jsp
    38. Features:: Error Handling
      • HandlerExceptionResolvers - handle unexpected exceptions
        • Programmatic exception handling
        • Information about what handler was executing when the exception was thrown
        • SimpleMappingExceptionResolver – map exception classes to views
    39. Features:: I18n
      • LocaleResolver
        • automatically resolve messages using the client's locale
          • AcceptHeaderLocaleResolver
          • CookieLocaleResolver
          • SessionLocaleResolver
      • LocaleChangeInterceptor
        • change the locale in specific cases
      • Reloadable resource bundles
    40. Features:: Documentation
      • Excellent reference documentation !
      • Books – mostly on the entire framework
      • Code samples
      • Many AppFuse QuickStart applications
    41. Summary
      • Introduction
      • Background
      • Features Review
        • Configuration
        • View technology
        • Page flow
        • Table sorting
        • Search results pagination
        • Validation
        • AJAX
        • Error handling
        • I18n
        • Documentation
      • Summary
    42. Summary:: Pros
      • Pros:
        • Highly flexible
        • Strong REST foundations
        • A wide choice of view technologies
        • New annotation configuration, less XML, more defaults
        • Integrates with many common web solutions
        • Easy adoption for Struts 1 users
    43. Summary:: Cons
      • Cons:
        • Model2 MVC forces you to build your application around request/response principles as dictated by HTTP
          • This was done by design in Spring MVC
        • Requires a lot of work in the presentation layer: JSP, Javascript, etc.
        • No AJAX support out of the box
        • No components support
    44. Summary:: Roadmap
      • Spring 3.0 – August/September 2008
        • Unification in the programming model between Spring Web Flow and Spring MVC
          • SpringFaces - JSF Integration
          • Spring JavaScript - abstraction over common JavaScript toolkits
          • AJAX support
          • Conversational state
    45. Summary:: References
      • http://springframework.org/
      • Spring Source
      • Spring Modules
      • Spring IDE
      • Appfuse light - spring MVC quickstarts
      • Matt Raible - Spring MVC
      • Expert Spring MVC and Web Flow
      • Thank
      • You !

    + yuvalbyuvalb, 2 years ago

    custom

    3600 views, 5 favs, 1 embeds more stats

    Spring MVC be Dror Bereznitsky from AlphaCSP
    www.al more

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 3600
      • 3599 on SlideShare
      • 1 from embeds
    • Comments 0
    • Favorites 5
    • Downloads 146
    Most viewed embeds
    • 1 views on http://www.clearspring.com

    more

    All embeds
    • 1 views on http://www.clearspring.com

    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