Your SlideShare is downloading. ×
  • Like
Spring 3.x - Spring MVC
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Spring 3.x - Spring MVC

  • 6,562 views
Published

 

Published in Technology , Education
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
  • Excellent article!
    Are you sure you want to
    Your message goes here
No Downloads

Views

Total Views
6,562
On SlideShare
0
From Embeds
0
Number of Embeds
1

Actions

Shares
Downloads
511
Comments
1
Likes
10

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 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
  • 3.
    • About 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
  • 6.
    • Architecture and design
  • 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
  • 22.
    • Handler mapping
  • 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 >
  • 26.
    • Controllers
  • 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 { ... }
  • 34.
    • View resolvers
  • 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
  • 38.
    • Annotation driven
  • 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