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
Spring-training-in-bangalore
TIB Academy
 
PDF
quickguide-einnovator-7-spring-mvc
jorgesimao71
 
PDF
Spring Framework-II
People Strategists
 
PDF
Spring MVC introduction HVA
Peter Maas
 
PPTX
Spring mvc
Hui Xie
 
PDF
Design & Development of Web Applications using SpringMVC
Naresh Chintalcheru
 
PPTX
Spring mvc
Pravin Pundge
 
PDF
Spring tutorial
Sanjoy Kumer Deb
 
PDF
REST based web applications with Spring 3
Oliver Gierke
 
PDF
Multi Client Development with Spring - Josh Long
jaxconf
 
PDF
Spring_Course_Content
MV Solutions
 
PDF
Orbitz and Spring Webflow Case Study
Mark Meeker
 
PDF
Spring MVC - The Basics
Ilio Catallo
 
PPT
Spring Framework
nomykk
 
PPT
Struts Overview
elliando dias
 
PPT
Spring training
TechFerry
 
PPTX
Spring mvc
Harshit Choudhary
 
PPTX
Spring mvc
nagarajupatangay
 
PPT
Struts2
yuvalb
 
PPTX
A project on spring framework by rohit malav
Rohit malav
 
Spring-training-in-bangalore
TIB Academy
 
quickguide-einnovator-7-spring-mvc
jorgesimao71
 
Spring Framework-II
People Strategists
 
Spring MVC introduction HVA
Peter Maas
 
Spring mvc
Hui Xie
 
Design & Development of Web Applications using SpringMVC
Naresh Chintalcheru
 
Spring mvc
Pravin Pundge
 
Spring tutorial
Sanjoy Kumer Deb
 
REST based web applications with Spring 3
Oliver Gierke
 
Multi Client Development with Spring - Josh Long
jaxconf
 
Spring_Course_Content
MV Solutions
 
Orbitz and Spring Webflow Case Study
Mark Meeker
 
Spring MVC - The Basics
Ilio Catallo
 
Spring Framework
nomykk
 
Struts Overview
elliando dias
 
Spring training
TechFerry
 
Spring mvc
Harshit Choudhary
 
Spring mvc
nagarajupatangay
 
Struts2
yuvalb
 
A project on spring framework by rohit malav
Rohit malav
 
Ad

Recently uploaded (20)

PPTX
Technical Analysis of 1st Generation Biofuel Feedstocks - 25th June 2025
TOFPIK
 
PDF
Your Best Year Yet​ Create a Sharp, Focused AOP for FY2026​
ChristopherVicGamuya
 
PDF
HOW TO RECOVER LOST CRYPTOCURRENCY - VISIT iBOLT CYBER HACKER COMPANY
diegovalentin771
 
PDF
Dr. Tran Quoc Bao - The Visionary Architect Behind Ho Chi Minh City’s Rise as...
Gorman Bain Capital
 
PDF
Native Sons Of The Golden West - Boasts A Legacy Of Impactful Leadership
Native Sons of the Golden West
 
PDF
"Complete Guide to the Partner Visa 2025
Zealand Immigration
 
PPTX
Business profile making an example ppt for small scales
Bindu222929
 
PDF
Step-by-Step: Buying a Verified Cash App Accounts| PDF | Payments Service
https://pvabulkpro.com/
 
PDF
Top Trends Redefining B2B Apparel Exporting in 2025
ananyaa2255
 
PPTX
25 Future Mega Trends Reshaping the World in 2025 and Beyond
presentifyai
 
PPTX
Melbourne’s Trusted Accountants for Business Tax - Clear Tax
Clear Tax
 
PDF
Maksym Vyshnivetskyi: Управління закупівлями (UA)
Lviv Startup Club
 
DOCX
TCP Communication Flag Txzczczxcxzzxypes.docx
esso24
 
PPTX
Revolutionizing Retail: The Impact of Artificial Intelligence
RUPAL AGARWAL
 
PPTX
Sustainability Strategy ESG Goals and Green Transformation Insights.pptx
presentifyai
 
PPTX
Delivering Excellence: Lessons from the FedEx Model
RaulAmavisca
 
PDF
3rd Edition of Human Resources Management Awards
resources7371
 
PDF
FastnersFastnersFastnersFastnersFastners
mizhanw168
 
PDF
NewBase 03 July 2025 Energy News issue - 1799 by Khaled Al Awadi_compressed.pdf
Khaled Al Awadi
 
PPTX
Oil and Gas EPC Market Size & Share | Growth - 2034
Aman Bansal
 
Technical Analysis of 1st Generation Biofuel Feedstocks - 25th June 2025
TOFPIK
 
Your Best Year Yet​ Create a Sharp, Focused AOP for FY2026​
ChristopherVicGamuya
 
HOW TO RECOVER LOST CRYPTOCURRENCY - VISIT iBOLT CYBER HACKER COMPANY
diegovalentin771
 
Dr. Tran Quoc Bao - The Visionary Architect Behind Ho Chi Minh City’s Rise as...
Gorman Bain Capital
 
Native Sons Of The Golden West - Boasts A Legacy Of Impactful Leadership
Native Sons of the Golden West
 
"Complete Guide to the Partner Visa 2025
Zealand Immigration
 
Business profile making an example ppt for small scales
Bindu222929
 
Step-by-Step: Buying a Verified Cash App Accounts| PDF | Payments Service
https://pvabulkpro.com/
 
Top Trends Redefining B2B Apparel Exporting in 2025
ananyaa2255
 
25 Future Mega Trends Reshaping the World in 2025 and Beyond
presentifyai
 
Melbourne’s Trusted Accountants for Business Tax - Clear Tax
Clear Tax
 
Maksym Vyshnivetskyi: Управління закупівлями (UA)
Lviv Startup Club
 
TCP Communication Flag Txzczczxcxzzxypes.docx
esso24
 
Revolutionizing Retail: The Impact of Artificial Intelligence
RUPAL AGARWAL
 
Sustainability Strategy ESG Goals and Green Transformation Insights.pptx
presentifyai
 
Delivering Excellence: Lessons from the FedEx Model
RaulAmavisca
 
3rd Edition of Human Resources Management Awards
resources7371
 
FastnersFastnersFastnersFastnersFastners
mizhanw168
 
NewBase 03 July 2025 Energy News issue - 1799 by Khaled Al Awadi_compressed.pdf
Khaled Al Awadi
 
Oil and Gas EPC Market Size & Share | Growth - 2034
Aman Bansal
 
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