Spring 3.x - Spring MVC
Upcoming SlideShare
Loading in...5
×
 

Spring 3.x - Spring MVC

on

  • 6,587 views

 

Statistics

Views

Total Views
6,587
Views on SlideShare
6,585
Embed Views
2

Actions

Likes
10
Downloads
466
Comments
1

1 Embed 2

http://www.linkedin.com 2

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • Excellent article!
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Spring 3.x - Spring MVC Spring 3.x - Spring MVC Presentation Transcript

    • 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