Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Spring 3.x - Spring MVC

8,520 views

Published on

Published in: Technology, Education

Spring 3.x - Spring MVC

  1. 1. <ul><li>Spring MVC </li></ul><ul><li>Guy Nir </li></ul><ul><li>January 2012 </li></ul>
  2. 2. <ul><li>About Spring MVC </li></ul><ul><li>Architecture and design </li></ul><ul><li>Handler mapping </li></ul><ul><li>Controllers </li></ul><ul><li>View resolvers </li></ul><ul><li>Annotation driven </li></ul><ul><li>Summary </li></ul><ul><li>Agenda </li></ul>Spring MVC
  3. 3. <ul><li>About Spring MVC </li></ul>
  4. 4. <ul><li>Top-level project at Spring framework </li></ul><ul><ul><li>Acknowledged that web is a crucial part of JEE world. </li></ul></ul><ul><ul><li>Provide first-class support for web technologies </li></ul></ul><ul><ul><ul><li>Markup generators (JSP, Velocity, Freemarker, etc …) </li></ul></ul></ul><ul><ul><ul><li>REST support. </li></ul></ul></ul><ul><li>Integrates web and Spring core. </li></ul><ul><li>About </li></ul>Spring MVC
  5. 5. <ul><li>Introduced with Spring 1.0 (August 2003) </li></ul><ul><li>Led by Rod Johnson and Juergen Hoeller </li></ul><ul><li>Introduced due the poor design of other frameworks </li></ul><ul><ul><li>Struts Jakarta </li></ul></ul><ul><li>About </li></ul><ul><li>History </li></ul>Spring MVC
  6. 6. <ul><li>Architecture and design </li></ul>
  7. 7. Spring MVC <ul><li>Architecture and design </li></ul>Servlet Application Context Spring MVC
  8. 8. <ul><li>Open-close principle [1] </li></ul><ul><ul><li>Open for extension, closed for modification. </li></ul></ul><ul><li>Convention over configuration. [2] </li></ul><ul><li>Model-View-Controller (MVC) driven. [3] </li></ul><ul><li>Clear separation of concerns. </li></ul><ul><li>Architecture and design </li></ul><ul><li>Design guidelines </li></ul>Spring MVC [1] Bob Martin, The Open-Closed Principle [2] Convention over configuration [3] Model View Controller – GoF design pattern
  9. 9. <ul><li>Tightly coupled with HTTP Servlet API. </li></ul><ul><li>Request-based model. </li></ul><ul><li>Takes a strategy approach. [4] </li></ul><ul><li>All activity surrounds the DispatcherServlet. </li></ul><ul><li>Architecture and design </li></ul><ul><li>Design guidelines - continued </li></ul>Spring MVC [4] Strategy – GoF design pattern
  10. 10. <ul><li>Architecture and design </li></ul><ul><li>web.xml </li></ul>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. 11. <ul><li>Architecture and design </li></ul><ul><li>Application context lookup </li></ul>Spring MVC <servlet-name> /WEB-INF/ <servlet-name> - servlet.xml petshop /WEB-INF/ petshop- servlet.xml
  12. 12. <ul><li>Architecture and design </li></ul><ul><li>Spring MVC approach </li></ul>Spring MVC
  13. 13. Spring MVC <ul><li>Architecture and design </li></ul>Dispatcher Servlet Incoming request Outgoing response Controller (Bean) Delegate Rendered response View renderer Model (JavaBean) 1 2 3 4 (?) 5 (?) 6 Application context
  14. 14. Spring MVC <ul><li>Architecture and design </li></ul>Dispatcher Servlet Controller View renderer
  15. 15. <ul><li>Dispatcher servlet flow </li></ul>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. 16. <ul><li>Dispatcher servlet flow </li></ul>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. 17. <ul><li>Dispatcher servlet flow </li></ul>Spring MVC Interceptors (postHandle) Incoming HTTP request Simple controller adapter Annotation-based adapter Another servlet adapter Handler adapter View renderer Exception handler Interceptors (preHandle) <ul><li>public interface HandlerInterceptor { </li></ul><ul><li>public boolean preHandle(HttpServletRequest request, </li></ul><ul><ul><ul><ul><ul><li> HttpServletResponse response, </li></ul></ul></ul></ul></ul><ul><li> Object handler) </li></ul><ul><li> throws Exception { </li></ul><ul><li>// Pre-processing callback. </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  18. 18. <ul><li>Dispatcher servlet flow </li></ul>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. 19. <ul><li>Dispatcher servlet flow </li></ul>Spring MVC Interceptors (preHandle) Incoming HTTP request Simple controller adapter Annotation-based adapter Another servlet adapter Handler adapter View renderer Exception handler <ul><li>public interface HandlerInterceptor { </li></ul><ul><li>public void postHandle(HttpServletRequest request, </li></ul><ul><ul><ul><ul><ul><li> HttpServletResponse response, </li></ul></ul></ul></ul></ul><ul><li> Object handler, </li></ul><ul><li> ModelAndView modelAndView ) </li></ul><ul><li> throws Exception { </li></ul><ul><li>// Post-processing callback. </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>Interceptors (postHandle)
  20. 20. <ul><li>Dispatcher servlet flow </li></ul>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 <ul><li>ResourceBundleViewResolver </li></ul><ul><li>UrlBasedViewResolver </li></ul><ul><li>FreeMarkerViewResolver </li></ul><ul><li>VelocityLayoutViewResolver </li></ul><ul><li>JasperReportsViewResolver </li></ul><ul><li>InternalResourceViewResolver </li></ul><ul><li>XsltViewResolver </li></ul><ul><li>TilesViewResolver </li></ul><ul><li>XmlViewResolver </li></ul><ul><li>BeanNameViewResolver </li></ul>
  21. 21. <ul><li>Dispatcher servlet flow </li></ul>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
  22. 22. <ul><li>Handler mapping </li></ul>
  23. 23. <ul><li>Maps between an incoming request and the appropriate controller. </li></ul><ul><li>Handler mapping </li></ul>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. 24. <ul><li>Dispatcher servlet: </li></ul><ul><ul><li>Search for all beans derived from org.springframework.web.servlet.HandlerMapping </li></ul></ul><ul><ul><li>Traverse all handlers. For each handler: </li></ul></ul><ul><ul><ul><li>Check if handler can resolve request to a controller. </li></ul></ul></ul><ul><ul><ul><li>Delegate control to the controller. </li></ul></ul></ul><ul><li>Handler mapping </li></ul>Spring MVC
  25. 25. <ul><li>Handler mapping </li></ul>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 >
  26. 26. <ul><li>Controllers </li></ul>
  27. 27. <ul><li>Controllers </li></ul>Spring MVC public interface Controller { public ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response) throws Exception; } View: Object ? Model: Key/Value map Model + View
  28. 28. <ul><li>Controllers </li></ul>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. 29. <ul><li>Controllers </li></ul>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. 30. <ul><li>Controllers </li></ul>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. 31. <ul><li>Controllers </li></ul>Spring MVC << interface >> Controller MyController Handle incoming requests
  32. 32. <ul><li>Controllers </li></ul>Spring MVC << interface >> Controller << abstract>> AbstractController MyController <ul><li>supportedMethods (GET, POST, …) </li></ul><ul><li>requireSession (true/false) </li></ul><ul><li>synchronize (true/false) </li></ul><ul><li>Cache control </li></ul>public ModelAndView handleRequest( HttpServletRequest request , HttpServletResponse response) throws Exception { ... }
  33. 33. <ul><li>Controllers </li></ul>Spring MVC << interface >> Controller << abstract>> AbstractController MyController << abstract>> AbstractUrlViewController Resolve controller based on URL public ModelAndView handleRequestInt( HttpServletRequest request , HttpServletResponse response) throws Exception { ... }
  34. 34. <ul><li>View resolvers </li></ul>
  35. 35. <ul><li>Resolve a view object to actual rendered output. </li></ul><ul><li>Isolate application logic from underlying view implementation. </li></ul><ul><ul><li>Each view is identified by a discrete object (e.g.: name). </li></ul></ul><ul><ul><li>Each view is resolved to a different renderer. </li></ul></ul><ul><li>View resolvers </li></ul>Spring MVC
  36. 36. <ul><li>View resolvers </li></ul>Spring MVC View resolver XmlViewResolver ResourceBundleViewResolver FreeMarkerViewResolver UrlBasedViewResolver View: “ login” View handlers
  37. 37. <ul><li>View resolvers </li></ul>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
  38. 38. <ul><li>Annotation driven </li></ul>
  39. 39. <ul><li>Allow us to specify all mapping and handling via annotations. </li></ul><ul><li>Annotation driven </li></ul>Spring MVC
  40. 40. <ul><li>Annotation driven </li></ul><ul><li>Basic request mapping </li></ul>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. 41. <ul><li>Annotation driven </li></ul><ul><li>Selecting method type </li></ul>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. 42. <ul><li>Annotation driven </li></ul><ul><li>Accessing request parameters </li></ul>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. 43. <ul><li>Annotation driven </li></ul><ul><li>Multiple handlers per controller </li></ul>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. 44. <ul><li>Annotation driven </li></ul><ul><li>URI template </li></ul>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. 45. <ul><li>Annotation driven </li></ul><ul><li>URI template </li></ul>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. 46. <ul><li>Annotation driven </li></ul><ul><li>Exception handling </li></ul>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. 47. <ul><li>Annotation driven </li></ul><ul><li>File upload example </li></ul>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. 48. <ul><li>Annotation driven </li></ul><ul><li>Cookies </li></ul>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. 49. <ul><li>Annotation driven </li></ul><ul><li>Session attributes </li></ul>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. 50. <ul><li>Annotation driven </li></ul><ul><li>Application context configuration </li></ul>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. 51. <ul><li>Annotation driven </li></ul><ul><li>Application context configuration - continued </li></ul>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. 52. <ul><li>Spring MVC provide a clear separation between a model, view and controller </li></ul><ul><li>Provide both XML-based and annotation-based approaches. </li></ul><ul><li>Enriched by Spring application context. </li></ul><ul><li>Provide a broad range of pre-configured facilities. </li></ul><ul><li>Takes convention over configuration approach. </li></ul><ul><li>Uses open-close principle. </li></ul><ul><li>Summary </li></ul>Spring MVC
  53. 53. <ul><li>Spring MVC reference guide: </li></ul><ul><ul><li>http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html </li></ul></ul><ul><li>Summary </li></ul><ul><li>References </li></ul>Spring MVC
  54. 54. <ul><li>Q & A </li></ul>

×