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
Ad

More Related Content

What's hot (19)

Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
zeeshanhanif
 
Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVC
John Lewis
 
Spring MVC Annotations
Spring MVC AnnotationsSpring MVC Annotations
Spring MVC Annotations
Jordan Silva
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
Tuna Tore
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
Guo Albert
 
Jsf intro
Jsf introJsf intro
Jsf intro
vantinhkhuc
 
JSF Component Behaviors
JSF Component BehaviorsJSF Component Behaviors
JSF Component Behaviors
Andy Schwartz
 
Spring MVC 3.0 Framework (sesson_2)
Spring MVC 3.0 Framework (sesson_2)Spring MVC 3.0 Framework (sesson_2)
Spring MVC 3.0 Framework (sesson_2)
Ravi Kant Soni ([email protected])
 
Spring 4 Web App
Spring 4 Web AppSpring 4 Web App
Spring 4 Web App
Rossen Stoyanchev
 
Java Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkJava Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC Framework
Guo Albert
 
A Complete Tour of JSF 2
A Complete Tour of JSF 2A Complete Tour of JSF 2
A Complete Tour of JSF 2
Jim Driscoll
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
BG Java EE Course
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
Dzmitry Naskou
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
John Lewis
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
Michał Orman
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
Aaron Schram
 
Struts,Jsp,Servlet
Struts,Jsp,ServletStruts,Jsp,Servlet
Struts,Jsp,Servlet
dasguptahirak
 
MVC on the server and on the client
MVC on the server and on the clientMVC on the server and on the client
MVC on the server and on the client
Sebastiano Armeli
 
Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVC
John Lewis
 
Spring MVC Annotations
Spring MVC AnnotationsSpring MVC Annotations
Spring MVC Annotations
Jordan Silva
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
Tuna Tore
 
JSF Component Behaviors
JSF Component BehaviorsJSF Component Behaviors
JSF Component Behaviors
Andy Schwartz
 
Java Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkJava Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC Framework
Guo Albert
 
A Complete Tour of JSF 2
A Complete Tour of JSF 2A Complete Tour of JSF 2
A Complete Tour of JSF 2
Jim Driscoll
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
BG Java EE Course
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
Dzmitry Naskou
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
John Lewis
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
Michał Orman
 
MVC on the server and on the client
MVC on the server and on the clientMVC on the server and on the client
MVC on the server and on the client
Sebastiano Armeli
 

Viewers also liked (12)

Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC framework
Mohit Gupta
 
Next stop: Spring 4
Next stop: Spring 4Next stop: Spring 4
Next stop: Spring 4
Oleg Tsal-Tsalko
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Serhat Can
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
Funnelll
 
Spring 3 MVC CodeMash 2009
Spring 3 MVC   CodeMash 2009Spring 3 MVC   CodeMash 2009
Spring 3 MVC CodeMash 2009
kensipe
 
Spring mvc my Faviourite Slide
Spring mvc my Faviourite SlideSpring mvc my Faviourite Slide
Spring mvc my Faviourite Slide
Daniel Adenew
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
Dhiraj Champawat
 
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorialsSpring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Raghavan Mohan
 
Spring 3 Annotated Development
Spring 3 Annotated DevelopmentSpring 3 Annotated Development
Spring 3 Annotated Development
kensipe
 
What's new in Spring 3?
What's new in Spring 3?What's new in Spring 3?
What's new in Spring 3?
Craig Walls
 
Spring @Transactional Explained
Spring @Transactional ExplainedSpring @Transactional Explained
Spring @Transactional Explained
Smita Prasad
 
MVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVCMVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVC
Anton Krasnoshchok
 
Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC framework
Mohit Gupta
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Serhat Can
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
Funnelll
 
Spring 3 MVC CodeMash 2009
Spring 3 MVC   CodeMash 2009Spring 3 MVC   CodeMash 2009
Spring 3 MVC CodeMash 2009
kensipe
 
Spring mvc my Faviourite Slide
Spring mvc my Faviourite SlideSpring mvc my Faviourite Slide
Spring mvc my Faviourite Slide
Daniel Adenew
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
Dhiraj Champawat
 
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorialsSpring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Raghavan Mohan
 
Spring 3 Annotated Development
Spring 3 Annotated DevelopmentSpring 3 Annotated Development
Spring 3 Annotated Development
kensipe
 
What's new in Spring 3?
What's new in Spring 3?What's new in Spring 3?
What's new in Spring 3?
Craig Walls
 
Spring @Transactional Explained
Spring @Transactional ExplainedSpring @Transactional Explained
Spring @Transactional Explained
Smita Prasad
 
MVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVCMVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVC
Anton Krasnoshchok
 
Ad

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

Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
micham
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
Tomi Juhola
 
What's Coming in Spring 3.0
What's Coming in Spring 3.0What's Coming in Spring 3.0
What's Coming in Spring 3.0
Matt Raible
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
goodfriday
 
my accadanic project ppt
my accadanic project pptmy accadanic project ppt
my accadanic project ppt
Manivel Thiruvengadam
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
ivpol
 
A portlet-API based approach for application integration
A portlet-API based approach for application integrationA portlet-API based approach for application integration
A portlet-API based approach for application integration
whabicht
 
ASP.NET MVC
ASP.NET MVCASP.NET MVC
ASP.NET MVC
Paul Stovell
 
Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2
Matt Raible
 
Unit 07: Design Patterns and Frameworks (3/3)
Unit 07: Design Patterns and Frameworks (3/3)Unit 07: Design Patterns and Frameworks (3/3)
Unit 07: Design Patterns and Frameworks (3/3)
DSBW 2011/2002 - Carles Farré - Barcelona Tech
 
CTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCCTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVC
Barry Gervin
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
AgileThought
 
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
Maarten Balliauw
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
Stefano Paluello
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
nagarajupatangay
 
springwebmvc-1234567891236547894463621.pdf
springwebmvc-1234567891236547894463621.pdfspringwebmvc-1234567891236547894463621.pdf
springwebmvc-1234567891236547894463621.pdf
Patiento Del Mar
 
Asp Net Architecture
Asp Net ArchitectureAsp Net Architecture
Asp Net Architecture
Juan Jose Gonzalez Faundez
 
ASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline Internals
Lukasz Lysik
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
Singapore PHP User Group
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
micham
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
Tomi Juhola
 
What's Coming in Spring 3.0
What's Coming in Spring 3.0What's Coming in Spring 3.0
What's Coming in Spring 3.0
Matt Raible
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
goodfriday
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
ivpol
 
A portlet-API based approach for application integration
A portlet-API based approach for application integrationA portlet-API based approach for application integration
A portlet-API based approach for application integration
whabicht
 
Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2
Matt Raible
 
CTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCCTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVC
Barry Gervin
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
AgileThought
 
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
Maarten Balliauw
 
springwebmvc-1234567891236547894463621.pdf
springwebmvc-1234567891236547894463621.pdfspringwebmvc-1234567891236547894463621.pdf
springwebmvc-1234567891236547894463621.pdf
Patiento Del Mar
 
ASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline Internals
Lukasz Lysik
 
Ad

Recently uploaded (20)

Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 

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