SlideShare a Scribd company logo
 
Spring MVC Dror Bereznitsky Senior Consultant and Architect, AlphaCSP It’s  Time
Agenda Introduction Background Features Review Configuration View technology Page flow Table sorting Search results pagination Validation AJAX Error handling I18n Documentation Summary
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
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
Introduction:: More Key Features Strong REST foundations Data Binding Framework Validation Framework Internationalization Support Tag Library
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
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
Agenda Introduction Background Features Review Configuration View technology Page flow Table sorting Search results pagination Validation AJAX Error handling I18n Documentation Summary
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
Background:: Request Handlers Incoming requests are dispatched to handlers There are potentially many handlers per Dispatcher Servlet Controllers are request handlers
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
Background:: Request Lifecycle Copyright 2006, www.springframework.org Handler
Features Review Introduction Background Features Review Configuration View technology Page flow Table sorting Search results pagination Validation AJAX Error handling I18n Documentation Summary
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
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
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
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
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>
Features:: Page Flow mv.setView( new  RedirectView(  &quot;../phoneBook“ ,   true ));
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
Page Flow – Step 1 Contd. DispatcherServlet PhoneBookController Handle GET /demo/phoneBook 1 InternalResource ViewResolver 2 phoneBook /WEB-INF/views/phoneBook.jsp phoneBook
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; ; }
Page Flow – Step 2 Contd. DispatcherServlet PhoneBookController Handle GET /demo/phoneBook 1 InternalResource ViewResolver 2 phoneBook /WEB-INF/views/phoneBook.jsp phoneBook
Features:: Sorting & Pagination Search results pagination Sorting by column
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
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
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)
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
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
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
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); …
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>
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;   />
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
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
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
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
Features:: I18n LocaleResolver  automatically resolve messages  using the client's locale  AcceptHeaderLocaleResolver CookieLocaleResolver SessionLocaleResolver LocaleChangeInterceptor change the locale in specific cases  Reloadable resource bundles
Features:: Documentation Excellent reference documentation ! Books – mostly on the entire framework Code samples Many AppFuse QuickStart applications
Summary Introduction Background Features Review Configuration View technology Page flow Table sorting Search results pagination Validation AJAX Error handling I18n Documentation Summary
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
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
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
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 !

More Related Content

What's hot (20)

PDF
Spring Framework - MVC
Dzmitry Naskou
 
PPTX
Spring MVC Architecture Tutorial
Java Success Point
 
PPT
Java Server Faces (JSF) - Basics
BG Java EE Course
 
PDF
SpringMVC
Akio Katayama
 
ODP
springmvc-150923124312-lva1-app6892
Tuna Tore
 
PPT
JSF Component Behaviors
Andy Schwartz
 
PPTX
Java Server Faces + Spring MVC Framework
Guo Albert
 
PDF
Jsf intro
vantinhkhuc
 
PDF
Spring mvc
Hamid Ghorbani
 
ODP
Annotation-Based Spring Portlet MVC
John Lewis
 
PDF
Introduction to Spring MVC
Richard Paul
 
PDF
Spring mvc
Guo Albert
 
ODP
A Complete Tour of JSF 2
Jim Driscoll
 
PDF
Spring MVC
Aaron Schram
 
PPTX
Spring framework in depth
Vinay Kumar
 
PDF
Spring MVC Framework
Hùng Nguyễn Huy
 
PDF
Spring MVC 3.0 Framework (sesson_2)
Ravi Kant Soni ([email protected])
 
PPT
Java Server Faces (JSF) - advanced
BG Java EE Course
 
PPT
Jsf2.0 -4
Vinay Kumar
 
PDF
Boston 2011 OTN Developer Days - Java EE 6
Arun Gupta
 
Spring Framework - MVC
Dzmitry Naskou
 
Spring MVC Architecture Tutorial
Java Success Point
 
Java Server Faces (JSF) - Basics
BG Java EE Course
 
SpringMVC
Akio Katayama
 
springmvc-150923124312-lva1-app6892
Tuna Tore
 
JSF Component Behaviors
Andy Schwartz
 
Java Server Faces + Spring MVC Framework
Guo Albert
 
Jsf intro
vantinhkhuc
 
Spring mvc
Hamid Ghorbani
 
Annotation-Based Spring Portlet MVC
John Lewis
 
Introduction to Spring MVC
Richard Paul
 
Spring mvc
Guo Albert
 
A Complete Tour of JSF 2
Jim Driscoll
 
Spring MVC
Aaron Schram
 
Spring framework in depth
Vinay Kumar
 
Spring MVC Framework
Hùng Nguyễn Huy
 
Spring MVC 3.0 Framework (sesson_2)
Ravi Kant Soni ([email protected])
 
Java Server Faces (JSF) - advanced
BG Java EE Course
 
Jsf2.0 -4
Vinay Kumar
 
Boston 2011 OTN Developer Days - Java EE 6
Arun Gupta
 

Similar to Spring MVC (20)

PPT
ASP.NET MVC introduction
Tomi Juhola
 
PPTX
Introduction to JSF
SoftServe
 
PPT
CTTDNUG ASP.NET MVC
Barry Gervin
 
PPTX
Entity framework and how to use it
nspyre_net
 
PPT
ASP.NET MVC Presentation
ivpol
 
PPT
Introduction to ASP.NET MVC
Maarten Balliauw
 
PPT
Introduction To ASP.NET MVC
Alan Dean
 
PPT
ASP.NET 3.5 SP1 (VSLive San Francisco 2009)
Dave Bost
 
PPT
Ta Javaserverside Eran Toch
Adil Jafri
 
PPS
Introduction To Mvc
Volkan Uzun
 
PDF
Build your website with angularjs and web apis
Chalermpon Areepong
 
PPT
Introduction to ASP.NET MVC
Sunpawet Somsin
 
PPTX
A Web Developer's Journey across different versions of ASP.NET
Harish Ranganathan
 
PPTX
Introduction to ASP.NET
Peter Gfader
 
PPT
Ibm
techbed
 
PPT
Spring and DWR
wiradikusuma
 
PPT
ASP.net MVC CodeCamp Presentation
buildmaster
 
PPTX
Overview of MVC Framework - by software outsourcing company india
Jignesh Aakoliya
 
PPT
Introduction to Alfresco Surf Platform
Alfresco Software
 
PPT
08052917365603
DSKUMAR G
 
ASP.NET MVC introduction
Tomi Juhola
 
Introduction to JSF
SoftServe
 
CTTDNUG ASP.NET MVC
Barry Gervin
 
Entity framework and how to use it
nspyre_net
 
ASP.NET MVC Presentation
ivpol
 
Introduction to ASP.NET MVC
Maarten Balliauw
 
Introduction To ASP.NET MVC
Alan Dean
 
ASP.NET 3.5 SP1 (VSLive San Francisco 2009)
Dave Bost
 
Ta Javaserverside Eran Toch
Adil Jafri
 
Introduction To Mvc
Volkan Uzun
 
Build your website with angularjs and web apis
Chalermpon Areepong
 
Introduction to ASP.NET MVC
Sunpawet Somsin
 
A Web Developer's Journey across different versions of ASP.NET
Harish Ranganathan
 
Introduction to ASP.NET
Peter Gfader
 
Ibm
techbed
 
Spring and DWR
wiradikusuma
 
ASP.net MVC CodeCamp Presentation
buildmaster
 
Overview of MVC Framework - by software outsourcing company india
Jignesh Aakoliya
 
Introduction to Alfresco Surf Platform
Alfresco Software
 
08052917365603
DSKUMAR G
 
Ad

Recently uploaded (20)

PDF
Thane Stenner - An Industry Expert
Thane Stenner
 
PPTX
Business Trendsjobsand careerr 2025.pptx
sahatanmay391
 
PPTX
Understanding ISO 42001 Standard: AI Governance & Compliance Insights from Ad...
Adeptiv AI
 
PDF
15 Essential Cloud Podcasts Every Tech Professional Should Know in 2025
Amnic
 
PDF
Connecting Startups to Strategic Global VC Opportunities.pdf
Google
 
PPTX
LESSON2.Uniquesellingpropositionandvalueproposition-180725234133.pptx
dioselasolidor1
 
PDF
From Legacy to Velocity: how we rebuilt everything in 8 months.
Product-Tech Team
 
PDF
LDM Recording for Yogi Goddess Projects Summer 2025
LDMMia GrandMaster
 
PDF
Van Aroma IFEAT - Clove Oils - Socio Economic Report .pdf
VanAroma
 
PDF
Concept Topology in Architectural Build Addendum.pdf
Brij Consulting, LLC
 
PPTX
Drive Operational Excellence with Proven Continuous Improvement Strategies
Group50 Consulting
 
PDF
Raman Bhaumik - A Passion For Service
Raman Bhaumik
 
DOCX
RECLAIM STOLEN CRYPTO REVIEW WITH RECUVA HACKER SOLUTIONS
camilamichaelj7
 
PDF
Concept topology- Architectural Build Design.pdf
Brij Consulting, LLC
 
PDF
David Badaro Explains 5 Steps to Solving Complex Business Issues
David Badaro
 
PDF
CBV - GST Collection Report V16. pdf.
writer28
 
PPTX
The Art of Customer Journey Optimization: Crafting Seamless Experiences
RUPAL AGARWAL
 
PDF
Rostyslav Chayka: Управління командою за допомогою AI (UA)
Lviv Startup Club
 
PPTX
Hackathon - Technology - Idea Submission Template -HackerEarth.pptx
nanster236
 
PPTX
Top RPA Tools to Watch in 2024: Transforming Automation
RUPAL AGARWAL
 
Thane Stenner - An Industry Expert
Thane Stenner
 
Business Trendsjobsand careerr 2025.pptx
sahatanmay391
 
Understanding ISO 42001 Standard: AI Governance & Compliance Insights from Ad...
Adeptiv AI
 
15 Essential Cloud Podcasts Every Tech Professional Should Know in 2025
Amnic
 
Connecting Startups to Strategic Global VC Opportunities.pdf
Google
 
LESSON2.Uniquesellingpropositionandvalueproposition-180725234133.pptx
dioselasolidor1
 
From Legacy to Velocity: how we rebuilt everything in 8 months.
Product-Tech Team
 
LDM Recording for Yogi Goddess Projects Summer 2025
LDMMia GrandMaster
 
Van Aroma IFEAT - Clove Oils - Socio Economic Report .pdf
VanAroma
 
Concept Topology in Architectural Build Addendum.pdf
Brij Consulting, LLC
 
Drive Operational Excellence with Proven Continuous Improvement Strategies
Group50 Consulting
 
Raman Bhaumik - A Passion For Service
Raman Bhaumik
 
RECLAIM STOLEN CRYPTO REVIEW WITH RECUVA HACKER SOLUTIONS
camilamichaelj7
 
Concept topology- Architectural Build Design.pdf
Brij Consulting, LLC
 
David Badaro Explains 5 Steps to Solving Complex Business Issues
David Badaro
 
CBV - GST Collection Report V16. pdf.
writer28
 
The Art of Customer Journey Optimization: Crafting Seamless Experiences
RUPAL AGARWAL
 
Rostyslav Chayka: Управління командою за допомогою AI (UA)
Lviv Startup Club
 
Hackathon - Technology - Idea Submission Template -HackerEarth.pptx
nanster236
 
Top RPA Tools to Watch in 2024: Transforming Automation
RUPAL AGARWAL
 
Ad

Spring MVC

  • 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; />
  • 19. Supported out of the box: JSP / JSTL XML / XSLT Apache Velocity Freemarker Adobe PDF Microsoft Excel Jasper Reports Features:: View Technology
  • 20. 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>
  • 21. Features:: Page Flow mv.setView( new RedirectView( &quot;../phoneBook“ , true ));
  • 22. 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
  • 23. Page Flow – Step 1 Contd. DispatcherServlet PhoneBookController Handle GET /demo/phoneBook 1 InternalResource ViewResolver 2 phoneBook /WEB-INF/views/phoneBook.jsp phoneBook
  • 24. 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; ; }
  • 25. Page Flow – Step 2 Contd. DispatcherServlet PhoneBookController Handle GET /demo/phoneBook 1 InternalResource ViewResolver 2 phoneBook /WEB-INF/views/phoneBook.jsp phoneBook
  • 26. Features:: Sorting & Pagination Search results pagination Sorting by column
  • 27. 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
  • 28. 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
  • 29. 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)
  • 30. 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
  • 31. 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
  • 32. 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
  • 33. 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); …
  • 34. 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>
  • 35. 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; />
  • 36. 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
  • 37. 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
  • 38. 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
  • 39. 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
  • 40. Features:: I18n LocaleResolver automatically resolve messages using the client's locale AcceptHeaderLocaleResolver CookieLocaleResolver SessionLocaleResolver LocaleChangeInterceptor change the locale in specific cases Reloadable resource bundles
  • 41. Features:: Documentation Excellent reference documentation ! Books – mostly on the entire framework Code samples Many AppFuse QuickStart applications
  • 42. Summary Introduction Background Features Review Configuration View technology Page flow Table sorting Search results pagination Validation AJAX Error handling I18n Documentation Summary
  • 43. 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
  • 44. 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
  • 45. 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
  • 46. 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