SlideShare a Scribd company logo
Spring MVC Guy Nir January 2012
About Spring MVC Architecture and design Handler mapping Controllers View resolvers Annotation driven Summary Agenda Spring MVC
About Spring MVC
Top-level project at Spring framework Acknowledged that web is a crucial part of JEE world. Provide first-class support for web technologies Markup generators (JSP, Velocity, Freemarker, etc …) REST support. Integrates web and Spring core. About Spring MVC
Introduced with Spring 1.0 (August 2003) Led by Rod Johnson and Juergen Hoeller Introduced due the poor design of other frameworks Struts Jakarta About History Spring MVC
Architecture and design
Spring MVC Architecture and design Servlet Application Context Spring MVC
Open-close principle  [1] Open for extension, closed for modification. Convention over configuration.  [2] Model-View-Controller (MVC) driven.  [3] Clear separation of concerns. Architecture and design Design guidelines Spring MVC [1]  Bob Martin, The Open-Closed  Principle [2]  Convention over configuration [3]  Model View Controller – GoF design pattern
Tightly coupled with HTTP Servlet API. Request-based model. Takes a strategy approach.  [4] All activity surrounds the DispatcherServlet. Architecture and design Design guidelines - continued Spring MVC [4]  Strategy – GoF design pattern
Architecture and design web.xml Spring MVC 1  <web-app> 2 3   <servlet> 4   <servlet-name> petshop </servlet-name> 5   <servlet-class> 6   org.springframework.web.servlet.DispatcherServlet 7   </servlet-class> 8   <load-on-startup>1</load-on-startup> 9   </servlet> 10 11   <servlet-mapping> 12   <servlet-name> petshop </servlet-name> 13   <url-pattern>*.do</url-pattern> 14   </servlet-mapping> 15   16  </web-app> Servlet name
Architecture and design Application context lookup Spring MVC <servlet-name> /WEB-INF/ <servlet-name> - servlet.xml petshop /WEB-INF/ petshop- servlet.xml
Architecture and design Spring MVC approach Spring MVC
Spring MVC Architecture and design Dispatcher Servlet Incoming request Outgoing response Controller (Bean) Delegate Rendered response View renderer Model (JavaBean) 1 2 3 4 (?) 5 (?) 6 Application context
Spring MVC Architecture and design Dispatcher Servlet Controller View renderer
Dispatcher servlet flow Spring MVC Incoming HTTP request Set locale Simple controller adapter Annotation-based adapter Another servlet adapter Interceptors (postHandle) Interceptors (preHandle) Handler adapter View renderer Locale View Themes Security authorization Exception handler
Dispatcher servlet flow Spring MVC Incoming HTTP request Set locale Simple controller adapter Annotation-based adapter Another servlet adapter Interceptors (postHandle) Interceptors (preHandle) Handler adapter View renderer Exception handler Locale View Themes Security authorization Controller View
Dispatcher servlet flow Spring MVC Interceptors (postHandle) Incoming HTTP request Simple controller adapter Annotation-based adapter Another servlet adapter Handler adapter View renderer Exception handler Interceptors (preHandle) public   interface  HandlerInterceptor { public boolean  preHandle(HttpServletRequest request,   HttpServletResponse response,   Object handler)   throws  Exception { // Pre-processing callback. } }
Dispatcher servlet flow Spring MVC Interceptors (preHandle) Interceptors (postHandle) Incoming HTTP request View renderer Exception handler Handler adapter Simple controller adapter Annotation-based adapter Another servlet adapter
Dispatcher servlet flow Spring MVC Interceptors (preHandle) Incoming HTTP request Simple controller adapter Annotation-based adapter Another servlet adapter Handler adapter View renderer Exception handler public   interface  HandlerInterceptor { public void  postHandle(HttpServletRequest request,   HttpServletResponse response,   Object handler,   ModelAndView modelAndView )   throws  Exception { // Post-processing callback. } } Interceptors (postHandle)
Dispatcher servlet flow Spring MVC Interceptors (postHandle) Interceptors (preHandle) Incoming HTTP request Simple controller adapter Annotation-based adapter Another servlet adapter Handler adapter Exception handler View renderer Locate current locale Render the appropriate view ResourceBundleViewResolver UrlBasedViewResolver FreeMarkerViewResolver VelocityLayoutViewResolver JasperReportsViewResolver InternalResourceViewResolver XsltViewResolver TilesViewResolver XmlViewResolver BeanNameViewResolver
Dispatcher servlet flow Spring MVC View renderer Interceptors (postHandle) Interceptors (preHandle) Incoming HTTP request Simple controller adapter Annotation-based adapter Another servlet adapter Handler adapter Exception handler DefaultHandlerExceptionResolver
Handler mapping
Maps between an incoming request and the appropriate controller. Handler mapping Spring MVC Incoming HTTP request Handler adapter Controller bean-name mapping Controller class-name mapping Static mapping Based on annotations [GET] http://host.com/services/userInfo.do Handlers from application context
Dispatcher servlet: Search for all beans derived from  org.springframework.web.servlet.HandlerMapping Traverse all handlers. For each handler: Check if handler can resolve request to a controller. Delegate control to the controller. Handler mapping Spring MVC
Handler mapping Spring MVC 1  <? xml  version = &quot;1.0&quot;  encoding = &quot;UTF-8&quot; ?> 2   3  < beans > 4   5   <!-- Map based on class name --> 6   < bean  class = &quot;org.springframework...ControllerClassNameHandlerMapping&quot; /> 7   8   <!-- Static mapping --> 9   < bean  class = &quot;org.springframework.web.servlet.handler.SimpleUrlHandlerMapping&quot; > 10   < property  name = &quot;mappings&quot; > 11   < value > 12   /info.do=personalInformationController 13   </ value > 14   </ property > 15   </ bean > 16   17   < bean  id = &quot;personalInformationController“ 18   class = &quot;com.cisco.mvc.controllers.PersonalInformationController&quot; /> 19   20  </ beans >
Controllers
Controllers Spring MVC public   interface  Controller { public  ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response)  throws  Exception; } View: Object ? Model: Key/Value map Model + View
Controllers Spring MVC 1  public   class  LoginController  implements  Controller { 2 3  @Override 4   public   ModelAndView   handleRequest(HttpServletRequest   request , 5     HttpServletResponse response) 6   throws   Exception   { 7   String username = request.getParameter( &quot;j_username&quot; ); 8   String password = request.getParameter( &quot;j_password&quot; ); 9   if   (!validateUser(username, password)) { 10   return   new   ModelAndView( &quot;invalidUsername.jsp&quot;, &quot;uname&quot;, username ); 11   }   else  { 12   return   new   ModelAndView( &quot;portal.jsp&quot; ); 13   } 14   } 15 16   private   boolean   validateUser(String username, String password) { 17   // Validate user ... 18   } 19  }
Controllers Spring MVC 1  public   class   LoginController   implements   Controller { 2 3  @Override 4   public   ModelAndView   handleRequest(HttpServletRequest   request , 5     HttpServletResponse response) 6   throws   Exception   { 7   String username = request.getParameter( &quot;j_username&quot; ); 8   String password = request.getParameter( &quot;j_password&quot; ); 9   if   (!validateUser(username, password)) { 10   int  retryCount = Integer.parseInt(request.getParameter( &quot;retries&quot; )); 11   Map<String, Object> model = new Map<String, Object>(); 12   model.put( &quot;uname&quot; , username); 13   model.put( “retryCount“,  retryCount + 1); 14 15   return   new   ModelAndView( &quot;invalidUsername.jsp&quot;,  model); 16   }   else  { 17   return   new   ModelAndView( &quot;portal.jsp&quot; ); 18   } 19   } 20  }
Controllers Spring MVC 1  public   class   LoginController   implements   Controller { 2 3  @Override 4   public   ModelAndView   handleRequest(HttpServletRequest   request , 5     HttpServletResponse response) 6   throws   Exception   { 7   String username = request.getParameter( &quot;j_username&quot; ); 8   String password = request.getParameter( &quot;j_password&quot; ); 9   if   (!validateUser(username, password)) { 10   int  retryCount = Integer.parseInt(request.getParameter( &quot;retries&quot; )); 11   Map<String, Object> model = new Map<String, Object>(); 12   model.put( &quot;uname&quot; , username); 13   model.put( “retryCount“,  retryCount + 1); 14 15   return   new   ModelAndView( &quot;invalidUsername.jsp&quot;,  model); 16   }   else  { 17   return   new   ModelAndView( &quot;portal.jsp&quot; ); 18   } 19   } 20  }
Controllers Spring MVC << interface >> Controller MyController Handle incoming requests
Controllers Spring MVC << interface >> Controller << abstract>> AbstractController MyController supportedMethods (GET, POST, …) requireSession (true/false) synchronize (true/false) Cache control public   ModelAndView   handleRequest( HttpServletRequest   request , HttpServletResponse response) throws   Exception   { ... }
Controllers Spring MVC << interface >> Controller << abstract>> AbstractController MyController << abstract>> AbstractUrlViewController Resolve controller based on URL public   ModelAndView   handleRequestInt( HttpServletRequest   request , HttpServletResponse response) throws   Exception   { ... }
View resolvers
Resolve a view object to actual rendered output. Isolate application logic from underlying view implementation. Each view is identified by a discrete object (e.g.: name). Each view is resolved to a different renderer. View resolvers Spring MVC
View resolvers Spring MVC View resolver XmlViewResolver ResourceBundleViewResolver FreeMarkerViewResolver UrlBasedViewResolver View: “ login” View handlers
View resolvers Spring MVC <? xml  version = &quot;1.0&quot;  encoding = &quot;UTF-8&quot; ?> < beans > < bean  id = &quot;viewResolver&quot; class = &quot;org.springframework.web.servlet.view.UrlBasedViewResolver&quot; > < property  name = &quot;prefix&quot;  value = &quot;/WEB-INF/pages/&quot;  /> < property  name = &quot;suffix&quot;  value = &quot;.jsp&quot;  /> </ bean > </ beans > View:  “login” /WEB-INF/pages/ login .jsp
Annotation driven
Allow us to specify all mapping and handling via annotations. Annotation driven Spring MVC
Annotation driven Basic request mapping Spring MVC 1 @Controller 2  public   class  CalcController { 3  4  // [GET] http://host.com/example/ calculate?first=NNN&second=MMM 5  @RequestMapping ( &quot;/calculate&quot; ) 6  public  String calculate(HttpServletRequest request) { 7  String first = request.getParameter( &quot;first&quot; ); 8  String second = request.getParameter( &quot;second&quot; ); 9  10  int  firstInt = Integer. parseInt(first); 11  int  secondInt = Integer. parseInt(second); 12  13  return  Integer. toString(firstInt + secondInt); 14  } 15  }
Annotation driven Selecting method type Spring MVC 1 @Controller 2  public   class  CalcController { 3  4  // [POST] http://host.com/example/ calculate?first=NNN&second=MMM 5  @RequestMapping (value =  &quot;/calculate&quot;,  method = RequestMethod.POST) 6  public  String calculate(HttpServletRequest request) { 7  String first = request.getParameter( &quot;first&quot; ); 8  String second = request.getParameter( &quot;second&quot; ); 9  10  int  firstInt = Integer. parseInt(first); 11  int  secondInt = Integer. parseInt(second); 12  13  return  Integer. toString(firstInt + secondInt); 14  } 15  }
Annotation driven Accessing request parameters Spring MVC 1 @Controller 2  public   class  CalcController { 3  4  // [POST] http://host.com/example/ calculate?first=NNN&second=MMM 5  @RequestMapping (value =  &quot;/calculate&quot;,  method = RequestMethod.POST) 6  public   String calculate(@RequestParam( &quot;first&quot; )  int  first, 7   @RequestParam( “second&quot; )  int  second)  { 8  return   Integer. toString(first + second); 9  } 10  }
Annotation driven Multiple handlers per controller Spring MVC 1 @Controller 2  public   class  CalcController { 3  4  // [POST] http://host.com/example/ calculate/add?first=NNN&second=MMM 5  @RequestMapping (value =  &quot;/calculate/add&quot;,  method = RequestMethod.POST) 6  public   String calculate(@RequestParam( &quot;first&quot; )  int  first, 7   @RequestParam( “second&quot; )  int  second)  { 8  return   Integer. toString(first + second); 9  } 4  // [POST] http://host.com/example/ calculate/sub?first=NNN&second=MMM 5  @RequestMapping (value =  &quot;/calculate/sub&quot;,  method = RequestMethod.GET) 6  public   String calculate(@RequestParam( &quot;first&quot; )  int  first, 7   @RequestParam( “second&quot; )  int  second)  { 8  return   Integer. toString(first - second); 9  } 10  }
Annotation driven URI template Spring MVC 1 @Controller 2  public   class  WeatherController { 3 4  // [GET] http://host.com /weather/972/TelAviv 5  @RequestMapping (value =  &quot;/weather/{countryCode}/{cityName}&quot; ) 6  public  ModelAndView getWeather( @PathVariable ( &quot;countryCode&quot; )  int  countryCode, 7  @PathVariable ( &quot;cityName&quot; ) String cityName) { 8  ModelAndView mav =  new  ModelAndView(); 9  // Fill in model the relevant information. 10  // Select a view appropriate for country. 11  return  mav; 12  } 13  }
Annotation driven URI template Spring MVC 1 @Controller 2  public   class  WeatherController { 3 4  // [GET] http://host.com /weather/972/TelAviv 5  @RequestMapping (value =  &quot;/weather/{countryCode}/{cityName}&quot; ) 6  public  ModelAndView getWeather( @PathVariable ( &quot;countryCode&quot; )  int  countryCode, 7  @PathVariable ( &quot;cityName&quot; ) String cityName) { 8  ModelAndView mav =  new  ModelAndView(); 9  // Fill in model the relevant information. 10  // Select a view appropriate for country. 11  return  mav; 12  } 13  }
Annotation driven Exception handling Spring MVC 1 @Controller 2  public   class  WeatherController { 3 4  @ExceptionHandler (IllegalArgumentException. class ) 5  public  String handleException(IllegalArgumentException ex, 6   HttpServletResponse response) { 7  return  ex.getMessage(); 8  } 9  }
Annotation driven File upload example Spring MVC @Controller public   class  FileUploadController { @RequestMapping (value =  &quot;/uploadFile&quot; , method = RequestMethod. POST ) public  String handleFormUpload( @RequestParam ( &quot;name&quot; ) String filename, @RequestParam ( &quot;file&quot; ) MultipartFile file) { if  (success) { return   &quot;redirect:uploadSuccess&quot; ; }  else  { return   &quot;redirect:uploadFailure&quot; ; } } }
Annotation driven Cookies Spring MVC @Controller public   class  FileUploadController { @RequestMapping (“/portal” ) public  String enterPortal( @CookieValue ( “lastVisited“ ) Date lastVisited) { } @RequestMapping (“/console” ) public  String enterPortal( @CookieValue (value =  “lastVisited“,  required =  “true” ) Date lastVisited) { } }
Annotation driven Session attributes Spring MVC 1 @Controller 2 @SessionAttributes ( &quot;userid&quot; ) 3  public   class  PersonalInformationController { 4  5  @RequestMapping ( &quot;/loginCheck&quot; ) 6  public  String checkUserLoggedIn( @ModelAttribute ( &quot;userid&quot; )  int  id)   { 7  // ... 8  } 9  }
Annotation driven Application context configuration Spring MVC 1  <? xml  version = &quot;1.0&quot;  encoding = &quot;UTF-8&quot; ?> 2  3  < beans > 4  5  <!-- Support for @Autowire --> 6  < context:annotation-config  /> 7  8  <!-- Support for @Controller --> 9  < context:component-scan  base-package = &quot;com.cisco.mvc&quot;  /> 10  11  <!-- Turn @Controller into actual web controllers--> 12  < mvc:annotation-driven /> 13  14  < mvc:interceptors > 15  </ mvc:interceptors > 16  17  </ beans >
Annotation driven Application context configuration - continued Spring MVC 1  <? xml  version = &quot;1.0&quot;  encoding = &quot;UTF-8&quot; ?> 2  3  < beans > 4  5  < mvc:interceptors > 6  < bean  class = &quot;com.cisco.mvc.interceptors.SecurityInterceptor&quot; /> 7  </ mvc:interceptors > 8  9  < mvc:resources  mapping = &quot;/static/**&quot;  location = &quot;/pages/&quot; /> 10 11   < mvc:view-controller  path = &quot;/&quot;  view-name = “homePage&quot; /> 12  13  </ beans >
Spring MVC provide a clear separation between a model, view and controller Provide both XML-based and annotation-based approaches. Enriched by Spring application context. Provide a broad range of pre-configured facilities. Takes convention over configuration approach. Uses open-close principle. Summary Spring MVC
Spring MVC reference guide: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html Summary References Spring MVC
Q & A

More Related Content

PPT
Spring MVC Basics
PPT
PPTX
Spring MVC
PPTX
Spring 3.x - Spring MVC - Advanced topics
ODP
Java Spring MVC Framework with AngularJS by Google and HTML5
PPT
Spring MVC
PPTX
Spring MVC Architecture Tutorial
PDF
Introduction to Spring MVC
Spring MVC Basics
Spring MVC
Spring 3.x - Spring MVC - Advanced topics
Java Spring MVC Framework with AngularJS by Google and HTML5
Spring MVC
Spring MVC Architecture Tutorial
Introduction to Spring MVC

What's hot (19)

PPTX
Spring Web MVC
ODP
Spring Portlet MVC
PDF
Spring MVC Annotations
PDF
SpringMVC
ODP
springmvc-150923124312-lva1-app6892
PDF
Spring mvc
PDF
Jsf intro
PPT
JSF Component Behaviors
PDF
Spring MVC 3.0 Framework (sesson_2)
PDF
Spring 4 Web App
PPTX
Java Server Faces + Spring MVC Framework
ODP
A Complete Tour of JSF 2
PPT
Java Server Faces (JSF) - advanced
PDF
Spring Framework - MVC
ODP
Annotation-Based Spring Portlet MVC
PPTX
Integration of Backbone.js with Spring 3.1
PDF
Spring MVC
PPT
Struts,Jsp,Servlet
KEY
MVC on the server and on the client
Spring Web MVC
Spring Portlet MVC
Spring MVC Annotations
SpringMVC
springmvc-150923124312-lva1-app6892
Spring mvc
Jsf intro
JSF Component Behaviors
Spring MVC 3.0 Framework (sesson_2)
Spring 4 Web App
Java Server Faces + Spring MVC Framework
A Complete Tour of JSF 2
Java Server Faces (JSF) - advanced
Spring Framework - MVC
Annotation-Based Spring Portlet MVC
Integration of Backbone.js with Spring 3.1
Spring MVC
Struts,Jsp,Servlet
MVC on the server and on the client
Ad

Viewers also liked (12)

PPTX
Spring MVC framework
PPTX
Next stop: Spring 4
PPTX
Introduction to Spring Framework
ODP
Introduction to Spring Framework and Spring IoC
PDF
Spring 3 MVC CodeMash 2009
PDF
Spring mvc my Faviourite Slide
DOCX
02 java spring-hibernate-experience-questions
PDF
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
PDF
Spring 3 Annotated Development
PDF
What's new in Spring 3?
PPTX
Spring @Transactional Explained
PPT
MVC Pattern. Flex implementation of MVC
Spring MVC framework
Next stop: Spring 4
Introduction to Spring Framework
Introduction to Spring Framework and Spring IoC
Spring 3 MVC CodeMash 2009
Spring mvc my Faviourite Slide
02 java spring-hibernate-experience-questions
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring 3 Annotated Development
What's new in Spring 3?
Spring @Transactional Explained
MVC Pattern. Flex implementation of MVC
Ad

Similar to Spring 3.x - Spring MVC (20)

PPTX
Spring mvc
PPTX
Spring mvc
PDF
quickguide-einnovator-7-spring-mvc
PPT
Spring-training-in-bangalore
PDF
Spring MVC introduction HVA
PDF
SpringMVC
PPTX
Spring mvc
PDF
Spring MVC - The Basics
PPTX
Spring WebApplication development
PDF
Spring MVC Framework
PPTX
3. Spring MVC Intro - PowerPoint Presentation (1).pptx
PDF
Spring tutorial
PPTX
A project on spring framework by rohit malav
PDF
Spring mvc 2.0
PDF
Multi Client Development with Spring - Josh Long
PDF
REST based web applications with Spring 3
PPT
Spring Framework
PPTX
Spring mvc
PPTX
Dispatcher
PDF
Spring Framework-II
Spring mvc
Spring mvc
quickguide-einnovator-7-spring-mvc
Spring-training-in-bangalore
Spring MVC introduction HVA
SpringMVC
Spring mvc
Spring MVC - The Basics
Spring WebApplication development
Spring MVC Framework
3. Spring MVC Intro - PowerPoint Presentation (1).pptx
Spring tutorial
A project on spring framework by rohit malav
Spring mvc 2.0
Multi Client Development with Spring - Josh Long
REST based web applications with Spring 3
Spring Framework
Spring mvc
Dispatcher
Spring Framework-II

Recently uploaded (20)

PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
KodekX | Application Modernization Development
PDF
Encapsulation theory and applications.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Big Data Technologies - Introduction.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Review of recent advances in non-invasive hemoglobin estimation
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Building Integrated photovoltaic BIPV_UPV.pdf
Programs and apps: productivity, graphics, security and other tools
The Rise and Fall of 3GPP – Time for a Sabbatical?
Understanding_Digital_Forensics_Presentation.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Network Security Unit 5.pdf for BCA BBA.
Agricultural_Statistics_at_a_Glance_2022_0.pdf
sap open course for s4hana steps from ECC to s4
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
Spectral efficient network and resource selection model in 5G networks
KodekX | Application Modernization Development
Encapsulation theory and applications.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Big Data Technologies - Introduction.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
cuic standard and advanced reporting.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Review of recent advances in non-invasive hemoglobin estimation

Spring 3.x - Spring MVC

  • 1. Spring MVC Guy Nir January 2012
  • 2. About Spring MVC Architecture and design Handler mapping Controllers View resolvers Annotation driven Summary Agenda Spring MVC
  • 4. Top-level project at Spring framework Acknowledged that web is a crucial part of JEE world. Provide first-class support for web technologies Markup generators (JSP, Velocity, Freemarker, etc …) REST support. Integrates web and Spring core. About Spring MVC
  • 5. Introduced with Spring 1.0 (August 2003) Led by Rod Johnson and Juergen Hoeller Introduced due the poor design of other frameworks Struts Jakarta About History Spring MVC
  • 7. Spring MVC Architecture and design Servlet Application Context Spring MVC
  • 8. Open-close principle [1] Open for extension, closed for modification. Convention over configuration. [2] Model-View-Controller (MVC) driven. [3] Clear separation of concerns. Architecture and design Design guidelines Spring MVC [1] Bob Martin, The Open-Closed Principle [2] Convention over configuration [3] Model View Controller – GoF design pattern
  • 9. Tightly coupled with HTTP Servlet API. Request-based model. Takes a strategy approach. [4] All activity surrounds the DispatcherServlet. Architecture and design Design guidelines - continued Spring MVC [4] Strategy – GoF design pattern
  • 10. Architecture and design web.xml Spring MVC 1 <web-app> 2 3 <servlet> 4 <servlet-name> petshop </servlet-name> 5 <servlet-class> 6 org.springframework.web.servlet.DispatcherServlet 7 </servlet-class> 8 <load-on-startup>1</load-on-startup> 9 </servlet> 10 11 <servlet-mapping> 12 <servlet-name> petshop </servlet-name> 13 <url-pattern>*.do</url-pattern> 14 </servlet-mapping> 15 16 </web-app> Servlet name
  • 11. Architecture and design Application context lookup Spring MVC <servlet-name> /WEB-INF/ <servlet-name> - servlet.xml petshop /WEB-INF/ petshop- servlet.xml
  • 12. Architecture and design Spring MVC approach Spring MVC
  • 13. Spring MVC Architecture and design Dispatcher Servlet Incoming request Outgoing response Controller (Bean) Delegate Rendered response View renderer Model (JavaBean) 1 2 3 4 (?) 5 (?) 6 Application context
  • 14. Spring MVC Architecture and design Dispatcher Servlet Controller View renderer
  • 15. Dispatcher servlet flow Spring MVC Incoming HTTP request Set locale Simple controller adapter Annotation-based adapter Another servlet adapter Interceptors (postHandle) Interceptors (preHandle) Handler adapter View renderer Locale View Themes Security authorization Exception handler
  • 16. Dispatcher servlet flow Spring MVC Incoming HTTP request Set locale Simple controller adapter Annotation-based adapter Another servlet adapter Interceptors (postHandle) Interceptors (preHandle) Handler adapter View renderer Exception handler Locale View Themes Security authorization Controller View
  • 17. Dispatcher servlet flow Spring MVC Interceptors (postHandle) Incoming HTTP request Simple controller adapter Annotation-based adapter Another servlet adapter Handler adapter View renderer Exception handler Interceptors (preHandle) public interface HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // Pre-processing callback. } }
  • 18. Dispatcher servlet flow Spring MVC Interceptors (preHandle) Interceptors (postHandle) Incoming HTTP request View renderer Exception handler Handler adapter Simple controller adapter Annotation-based adapter Another servlet adapter
  • 19. Dispatcher servlet flow Spring MVC Interceptors (preHandle) Incoming HTTP request Simple controller adapter Annotation-based adapter Another servlet adapter Handler adapter View renderer Exception handler public interface HandlerInterceptor { public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView ) throws Exception { // Post-processing callback. } } Interceptors (postHandle)
  • 20. Dispatcher servlet flow Spring MVC Interceptors (postHandle) Interceptors (preHandle) Incoming HTTP request Simple controller adapter Annotation-based adapter Another servlet adapter Handler adapter Exception handler View renderer Locate current locale Render the appropriate view ResourceBundleViewResolver UrlBasedViewResolver FreeMarkerViewResolver VelocityLayoutViewResolver JasperReportsViewResolver InternalResourceViewResolver XsltViewResolver TilesViewResolver XmlViewResolver BeanNameViewResolver
  • 21. Dispatcher servlet flow Spring MVC View renderer Interceptors (postHandle) Interceptors (preHandle) Incoming HTTP request Simple controller adapter Annotation-based adapter Another servlet adapter Handler adapter Exception handler DefaultHandlerExceptionResolver
  • 23. Maps between an incoming request and the appropriate controller. Handler mapping Spring MVC Incoming HTTP request Handler adapter Controller bean-name mapping Controller class-name mapping Static mapping Based on annotations [GET] http://host.com/services/userInfo.do Handlers from application context
  • 24. Dispatcher servlet: Search for all beans derived from org.springframework.web.servlet.HandlerMapping Traverse all handlers. For each handler: Check if handler can resolve request to a controller. Delegate control to the controller. Handler mapping Spring MVC
  • 25. Handler mapping Spring MVC 1 <? xml version = &quot;1.0&quot; encoding = &quot;UTF-8&quot; ?> 2 3 < beans > 4 5 <!-- Map based on class name --> 6 < bean class = &quot;org.springframework...ControllerClassNameHandlerMapping&quot; /> 7 8 <!-- Static mapping --> 9 < bean class = &quot;org.springframework.web.servlet.handler.SimpleUrlHandlerMapping&quot; > 10 < property name = &quot;mappings&quot; > 11 < value > 12 /info.do=personalInformationController 13 </ value > 14 </ property > 15 </ bean > 16 17 < bean id = &quot;personalInformationController“ 18 class = &quot;com.cisco.mvc.controllers.PersonalInformationController&quot; /> 19 20 </ beans >
  • 27. Controllers Spring MVC public interface Controller { public ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response) throws Exception; } View: Object ? Model: Key/Value map Model + View
  • 28. Controllers Spring MVC 1 public class LoginController implements Controller { 2 3 @Override 4 public ModelAndView handleRequest(HttpServletRequest request , 5 HttpServletResponse response) 6 throws Exception { 7 String username = request.getParameter( &quot;j_username&quot; ); 8 String password = request.getParameter( &quot;j_password&quot; ); 9 if (!validateUser(username, password)) { 10 return new ModelAndView( &quot;invalidUsername.jsp&quot;, &quot;uname&quot;, username ); 11 } else { 12 return new ModelAndView( &quot;portal.jsp&quot; ); 13 } 14 } 15 16 private boolean validateUser(String username, String password) { 17 // Validate user ... 18 } 19 }
  • 29. Controllers Spring MVC 1 public class LoginController implements Controller { 2 3 @Override 4 public ModelAndView handleRequest(HttpServletRequest request , 5 HttpServletResponse response) 6 throws Exception { 7 String username = request.getParameter( &quot;j_username&quot; ); 8 String password = request.getParameter( &quot;j_password&quot; ); 9 if (!validateUser(username, password)) { 10 int retryCount = Integer.parseInt(request.getParameter( &quot;retries&quot; )); 11 Map<String, Object> model = new Map<String, Object>(); 12 model.put( &quot;uname&quot; , username); 13 model.put( “retryCount“, retryCount + 1); 14 15 return new ModelAndView( &quot;invalidUsername.jsp&quot;, model); 16 } else { 17 return new ModelAndView( &quot;portal.jsp&quot; ); 18 } 19 } 20 }
  • 30. Controllers Spring MVC 1 public class LoginController implements Controller { 2 3 @Override 4 public ModelAndView handleRequest(HttpServletRequest request , 5 HttpServletResponse response) 6 throws Exception { 7 String username = request.getParameter( &quot;j_username&quot; ); 8 String password = request.getParameter( &quot;j_password&quot; ); 9 if (!validateUser(username, password)) { 10 int retryCount = Integer.parseInt(request.getParameter( &quot;retries&quot; )); 11 Map<String, Object> model = new Map<String, Object>(); 12 model.put( &quot;uname&quot; , username); 13 model.put( “retryCount“, retryCount + 1); 14 15 return new ModelAndView( &quot;invalidUsername.jsp&quot;, model); 16 } else { 17 return new ModelAndView( &quot;portal.jsp&quot; ); 18 } 19 } 20 }
  • 31. Controllers Spring MVC << interface >> Controller MyController Handle incoming requests
  • 32. Controllers Spring MVC << interface >> Controller << abstract>> AbstractController MyController supportedMethods (GET, POST, …) requireSession (true/false) synchronize (true/false) Cache control public ModelAndView handleRequest( HttpServletRequest request , HttpServletResponse response) throws Exception { ... }
  • 33. Controllers Spring MVC << interface >> Controller << abstract>> AbstractController MyController << abstract>> AbstractUrlViewController Resolve controller based on URL public ModelAndView handleRequestInt( HttpServletRequest request , HttpServletResponse response) throws Exception { ... }
  • 35. Resolve a view object to actual rendered output. Isolate application logic from underlying view implementation. Each view is identified by a discrete object (e.g.: name). Each view is resolved to a different renderer. View resolvers Spring MVC
  • 36. View resolvers Spring MVC View resolver XmlViewResolver ResourceBundleViewResolver FreeMarkerViewResolver UrlBasedViewResolver View: “ login” View handlers
  • 37. View resolvers Spring MVC <? xml version = &quot;1.0&quot; encoding = &quot;UTF-8&quot; ?> < beans > < bean id = &quot;viewResolver&quot; class = &quot;org.springframework.web.servlet.view.UrlBasedViewResolver&quot; > < property name = &quot;prefix&quot; value = &quot;/WEB-INF/pages/&quot; /> < property name = &quot;suffix&quot; value = &quot;.jsp&quot; /> </ bean > </ beans > View: “login” /WEB-INF/pages/ login .jsp
  • 39. Allow us to specify all mapping and handling via annotations. Annotation driven Spring MVC
  • 40. Annotation driven Basic request mapping Spring MVC 1 @Controller 2 public class CalcController { 3 4 // [GET] http://host.com/example/ calculate?first=NNN&second=MMM 5 @RequestMapping ( &quot;/calculate&quot; ) 6 public String calculate(HttpServletRequest request) { 7 String first = request.getParameter( &quot;first&quot; ); 8 String second = request.getParameter( &quot;second&quot; ); 9 10 int firstInt = Integer. parseInt(first); 11 int secondInt = Integer. parseInt(second); 12 13 return Integer. toString(firstInt + secondInt); 14 } 15 }
  • 41. Annotation driven Selecting method type Spring MVC 1 @Controller 2 public class CalcController { 3 4 // [POST] http://host.com/example/ calculate?first=NNN&second=MMM 5 @RequestMapping (value = &quot;/calculate&quot;, method = RequestMethod.POST) 6 public String calculate(HttpServletRequest request) { 7 String first = request.getParameter( &quot;first&quot; ); 8 String second = request.getParameter( &quot;second&quot; ); 9 10 int firstInt = Integer. parseInt(first); 11 int secondInt = Integer. parseInt(second); 12 13 return Integer. toString(firstInt + secondInt); 14 } 15 }
  • 42. Annotation driven Accessing request parameters Spring MVC 1 @Controller 2 public class CalcController { 3 4 // [POST] http://host.com/example/ calculate?first=NNN&second=MMM 5 @RequestMapping (value = &quot;/calculate&quot;, method = RequestMethod.POST) 6 public String calculate(@RequestParam( &quot;first&quot; ) int first, 7 @RequestParam( “second&quot; ) int second) { 8 return Integer. toString(first + second); 9 } 10 }
  • 43. Annotation driven Multiple handlers per controller Spring MVC 1 @Controller 2 public class CalcController { 3 4 // [POST] http://host.com/example/ calculate/add?first=NNN&second=MMM 5 @RequestMapping (value = &quot;/calculate/add&quot;, method = RequestMethod.POST) 6 public String calculate(@RequestParam( &quot;first&quot; ) int first, 7 @RequestParam( “second&quot; ) int second) { 8 return Integer. toString(first + second); 9 } 4 // [POST] http://host.com/example/ calculate/sub?first=NNN&second=MMM 5 @RequestMapping (value = &quot;/calculate/sub&quot;, method = RequestMethod.GET) 6 public String calculate(@RequestParam( &quot;first&quot; ) int first, 7 @RequestParam( “second&quot; ) int second) { 8 return Integer. toString(first - second); 9 } 10 }
  • 44. Annotation driven URI template Spring MVC 1 @Controller 2 public class WeatherController { 3 4 // [GET] http://host.com /weather/972/TelAviv 5 @RequestMapping (value = &quot;/weather/{countryCode}/{cityName}&quot; ) 6 public ModelAndView getWeather( @PathVariable ( &quot;countryCode&quot; ) int countryCode, 7 @PathVariable ( &quot;cityName&quot; ) String cityName) { 8 ModelAndView mav = new ModelAndView(); 9 // Fill in model the relevant information. 10 // Select a view appropriate for country. 11 return mav; 12 } 13 }
  • 45. Annotation driven URI template Spring MVC 1 @Controller 2 public class WeatherController { 3 4 // [GET] http://host.com /weather/972/TelAviv 5 @RequestMapping (value = &quot;/weather/{countryCode}/{cityName}&quot; ) 6 public ModelAndView getWeather( @PathVariable ( &quot;countryCode&quot; ) int countryCode, 7 @PathVariable ( &quot;cityName&quot; ) String cityName) { 8 ModelAndView mav = new ModelAndView(); 9 // Fill in model the relevant information. 10 // Select a view appropriate for country. 11 return mav; 12 } 13 }
  • 46. Annotation driven Exception handling Spring MVC 1 @Controller 2 public class WeatherController { 3 4 @ExceptionHandler (IllegalArgumentException. class ) 5 public String handleException(IllegalArgumentException ex, 6 HttpServletResponse response) { 7 return ex.getMessage(); 8 } 9 }
  • 47. Annotation driven File upload example Spring MVC @Controller public class FileUploadController { @RequestMapping (value = &quot;/uploadFile&quot; , method = RequestMethod. POST ) public String handleFormUpload( @RequestParam ( &quot;name&quot; ) String filename, @RequestParam ( &quot;file&quot; ) MultipartFile file) { if (success) { return &quot;redirect:uploadSuccess&quot; ; } else { return &quot;redirect:uploadFailure&quot; ; } } }
  • 48. Annotation driven Cookies Spring MVC @Controller public class FileUploadController { @RequestMapping (“/portal” ) public String enterPortal( @CookieValue ( “lastVisited“ ) Date lastVisited) { } @RequestMapping (“/console” ) public String enterPortal( @CookieValue (value = “lastVisited“, required = “true” ) Date lastVisited) { } }
  • 49. Annotation driven Session attributes Spring MVC 1 @Controller 2 @SessionAttributes ( &quot;userid&quot; ) 3 public class PersonalInformationController { 4 5 @RequestMapping ( &quot;/loginCheck&quot; ) 6 public String checkUserLoggedIn( @ModelAttribute ( &quot;userid&quot; ) int id) { 7 // ... 8 } 9 }
  • 50. Annotation driven Application context configuration Spring MVC 1 <? xml version = &quot;1.0&quot; encoding = &quot;UTF-8&quot; ?> 2 3 < beans > 4 5 <!-- Support for @Autowire --> 6 < context:annotation-config /> 7 8 <!-- Support for @Controller --> 9 < context:component-scan base-package = &quot;com.cisco.mvc&quot; /> 10 11 <!-- Turn @Controller into actual web controllers--> 12 < mvc:annotation-driven /> 13 14 < mvc:interceptors > 15 </ mvc:interceptors > 16 17 </ beans >
  • 51. Annotation driven Application context configuration - continued Spring MVC 1 <? xml version = &quot;1.0&quot; encoding = &quot;UTF-8&quot; ?> 2 3 < beans > 4 5 < mvc:interceptors > 6 < bean class = &quot;com.cisco.mvc.interceptors.SecurityInterceptor&quot; /> 7 </ mvc:interceptors > 8 9 < mvc:resources mapping = &quot;/static/**&quot; location = &quot;/pages/&quot; /> 10 11 < mvc:view-controller path = &quot;/&quot; view-name = “homePage&quot; /> 12 13 </ beans >
  • 52. Spring MVC provide a clear separation between a model, view and controller Provide both XML-based and annotation-based approaches. Enriched by Spring application context. Provide a broad range of pre-configured facilities. Takes convention over configuration approach. Uses open-close principle. Summary Spring MVC
  • 53. Spring MVC reference guide: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html Summary References Spring MVC
  • 54. Q & A