• Save
Spring MVC -  The Basics
Upcoming SlideShare
Loading in...5
×
 

Spring MVC - The Basics

on

  • 480 views

An introduction to the basics of the Spring MVC web framework. The concepts of front controller, controller (handler), model and view are introduced. The whole processing pipeline is discussed, with ...

An introduction to the basics of the Spring MVC web framework. The concepts of front controller, controller (handler), model and view are introduced. The whole processing pipeline is discussed, with an in-depth description of the HandlerMapping and ViewResolver strategy interfaces. The alternative representations of the Model (Map, Model and ModelMap) are presented.

Statistics

Views

Total Views
480
Views on SlideShare
477
Embed Views
3

Actions

Likes
3
Downloads
0
Comments
0

2 Embeds 3

http://ease-the-computation.haunted.io 2
http://www.slideee.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

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…
Post Comment
Edit your comment

Spring MVC -  The Basics Spring MVC - The Basics Presentation Transcript

  • Spring MVC – The Basics Ilio Catallo – Politecnico di Milano ilio.catallo@polimi.it
  • Outline ¤  MVC vs. web applications ¤  Spring MVC request processing pipeline ¤  Setting up the DispatcherServlet ¤  Writing Controllers ¤  Writing Views ¤  References 2
  • MVC vs. web applications
  • Model-View-Controller design pattern ¤  In the late seventies, software architects saw applications as having three major parts: ¤  The part that manages the data (Model) ¤  The part that creates screens and reports (View) ¤  The part that handles interactions between the user and the other subsystems (Controller) ¤  MVC turned out to be a good way to design applications ¤  Cocoa (Apple) ¤  Swing (Java) ¤  .NET (Microsoft) 4
  • Model-View-Controller design pattern 5 View Controller Model State query Change notification Event Method invocation
  • Model-View-Controller vs. Web applications ¤  Java developers already have utilities for: ¤  building presentation pages, e.g., JavaServer Pages ¤  handling databases, e.g., JDBC and JPA 6 What is the reason not to use the same MVC pattern also for web applications?
  • Model-View-Controller vs. Web applications ¤  But… ¤  the HTTP protocol imposes limitations on the applicability of the MVC design pattern ¤  we don’t have any component to act as the Controller 7 What is the reason not to use the same MVC pattern also for web applications?
  • HTTP limitations (1) ¤  The MVC design pattern requires a push protocol for the views to be notified by the model ¤  HTTP is a pull protocol: no request implies no response ¤  The MVC design pattern requires a stateful protocol to keep track of the state of the application ¤  HTTP is stateless 8
  • HTTP limitations (2) ¤  HTTP is stateless: we can implement the MVC design pattern on top of the Java Servlet Platform ¤  the platform provides a session context to help track users in the application ¤  HTTP is a pull protocol: we can increase the Controller responsibility. It will be responsible for: ¤  state changes ¤  state queries ¤  change notifications 9
  • Model-View-Controller 2 design pattern ¤  The resulting design pattern is sometimes called MVC2 or Web MVC ¤  Any state query or change notification must pass through the Controller ¤  The View renders data passed by the Controller rather than data returned directly from the Model 10 View Controller Model
  • What is Spring MVC? ¤  Spring MVC is an open source MVC2 framework for developing web application ¤  It eases web applications development by ¤  providing developers with a ready-to-use MVC2-style controller ¤  promoting Spring’s loosely coupled techniques in the presentation layer of an application 11
  • Spring MVC request processing pipeline
  • DispatcherServlet ¤  Spring’s web MVC framework is designed around a central servlet named DispatcherServlet Dispatcher Servlet Presentation layer 13
  • DispatcherServlet ¤  DispatcherServlet acts as a centralized entry point to the web application ¤  Every request is handled by DispatcherServlet Browser Dispatcher Servlet Presentation layer Request 14
  • DispatcherServlet ¤  DispatcherServlet is an expression of the Front Controller pattern Browser Front Controller Presentation layer Request 15
  • The Front Controller ¤  the Front controller’s job is to determine a suitable handler capable of perfoming the actual processing Browser Front Controller Presentation layer Request Handler Invokes 16
  • Controllers ¤  In the vast majority of cases, request handlers are Spring MVC Controllers Browser Front Controller Presentation layer Request Controller Invokes 17
  • Model ¤  Controllers harnesses user inputs in order to process and update the model Service layer Persistence layer DB Browser Front Controller Presentation layer Request Controller 18
  • Model ¤  Controllers harnesses user inputs in order to process and update the model Service layer Persistence layer DB Browser Front Controller Presentation layer Request Controller Model 19
  • Views ¤  When the controller has finished processing, the front controller determines which view to render Service layer Persistence layer DB Browser Front Controller Presentation layer Request Controller Model View 20
  • Views ¤  When the controller has finished processing, the front controller determines which view to render Service layer Persistence layer DB Browser Front Controller Presentation layer Request Controller Model View Model 21
  • Views ¤  When the controller has finished processing, the front controller determines which view to render Service layer Persistence layer DB Browser Front Controller Presentation layer Request Controller Model View Model 22
  • Views ¤  When the controller has finished processing, the front controller determines which view to render Service layer Persistence layer DB Browser Front Controller Presentation layer Request Controller Model View Model Response 23
  • Setting up the DispatcherServlet
  • Setting up the DispatcherServlet ¤  Setting up the DispatcherServlet is a two step process ¤  Namely: ¤  Declaration step: bootstrap the servlet in the web container ¤  Initialization step: instantiate the beans defined in the DI container 25
  • DispatcherServlet: declaration step ¤  Like any servlet, the DispatcherServlet needs to be set up so that the web container can bootstrap the servlet Web container Dispatcher Servlet 26
  • DispatcherServlet: declaration step ¤  Specifically, we need to tell the web container: ¤  to load the DispatcherServlet ¤  to map it to one ore more URL patterns ¤  The traditional way to instruct the web container is by means of the web.xml deployment descriptor file ¤  The web.xml file describes how to deploy web components in a web container 27
  • DispatcherServlet: declaration step <servlet> <servlet-name>frontcontroller</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>frontcontroller</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> Loadthe DispatcherSerlvet Map URLpatterns 28
  • DispatcherServlet: initialization step ¤  When created, DispatcherServlet instantiates a WebApplicationContext implementation ¤  The WebApplicationContext is the DI container we are going to use in the presentation layer ¤  WebApplicationContext extends the ApplicationContext interface with some extra features necessary for web applications <<interface>> BeanFactory <<interface>> ApplicationContext <<interface>> WebApplicationContext 29
  • Configuring WebApplicationContext ¤  As any Spring DI container, WebApplicationContext has to be provided with some configuration metatadata ¤  Spring MVC looks for the configuration metadata in a XML file named [frontcontroller]-servlet.xml ¤  frontcontroller is the <servlet-name> we specified in web.xml for the DispatcherServlet ¤  The file has to be placed in the WEB-INF/ folder 30
  • Configuration metadata ¤  [frontcontroller]-servlet.xml configuration metadata: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=”..."> <!-- CONFIGURE CONTROLLERS AND SPECIAL BEANS HERE --> </beans> 31
  • DispatcherServlet: initialization step ¤  The WebApplicationContext hosts two types of beans ¤  Namely: ¤  The controllers: controllers are written by the developer and provide access to the service layer of the application ¤  Special beans: the DispatcherServlet relies on special beans to process requests and render the appropriate views ¤  Controllers and special beans are the web-specific components of our application 32
  • WebApplication Context DispatcherServlet (awaiting incoming requests) WebApplicationContext Controller Controller Controllers ViewResolver Handler Mapping ¤  Among others, ViewResolver and HandlerMapping are two special beans needed by DispatcherServlet 33
  • Request processing pipeline ¤  The request processing pipeline is highly flexible and configurable Service layer Persistence layer DB Browser Front Controller Presentation layer Request Controller Model View Model Response 34
  • Interfaces = flexibility ¤  The flexibility comes from the fact that: ¤  Each special bean play its own small part in the overall processing of the request ¤  Each special bean is expressed as an interface 35
  • Special beans ¤  (Some) special beans: Special beans Purpose HandlerMapping Maps requests to handlers (e.g., Controllers) ViewResolver Maps view name to views HandlerExpectionResolver Maps exception to handlers and views LocaleResolver Resolves the locale of a request 36
  • HandlerMapping implementations ¤  Example: HandlerMapping «interface» HandlerMapping BeanNameUrlhandlerMapping DefaultAnnotationHandlerMapping SimpleUrlHandlerMapping 37
  • Default special beans ¤  For each special bean the DispatcherServlet maintains a list of implementations to use by default ¤  Example: DefaultAnnotationHandlerMapping is instantiated by default ¤  In order to customize on or more properties of a given special bean, it is sufficient to configure that special bean in the WebApplicationContext 38
  • Override default special beans ¤  Example: use InternalResourceViewResolver as ViewResolver strategy <bean class="org.springframework.web. servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> Customizations to InternalResourceViewResolver are injected via setter-based injection 39
  • Writing Controllers
  • Controllers respond to user’s actions ¤  The controller is the component that is responsible for responding to the action the user takes on the user interface (view) ¤  These actions could be: ¤  Form submission ¤  Clicking on a link ¤  Accessing a page 41
  • Two ways of building controllers ¤  With Spring MVC we have two options when writing controllers: ¤  Writing a class that Implements the Controller interface ¤  Writing a class and put the @Controller annotation on that class ¤  Even though the main focus will be on the annotation- based approach, interface-based controllers may still be useful in specific situations 42
  • Annotation-based controllers ¤  To write an annotation-based controller we need to use the @Controller annotation ¤  The @Controller annotation indicates that a particular class serves the role of a controller @Controller public class HelloWorldController { ... } 43
  • Auto-detecting controllers ¤  Annotated controllers can be auto-detected by adding the <context:component-scan> element to the [frontcontroller]-servlet.xml file ¤  The <context:component-scan> element works by recursively scanning a package, looking for classes that can be automatically registered as beans <context:component-scan base-package="it.polimi.awt.springmvc.web"/> 44
  • @RequestMapping maps URL to handler methods ¤  A Controller class is made of handler methods ¤  Handler methods are annotated with the @RequestMapping annotation @Controller public class HelloWorldController { @RequestMapping("/sayHelloWorld") public ModelAndView sayHelloWorld() { ... } } 45
  • @RequestMapping maps URL to handler methods ¤  The @RequestMapping annotation is used to map URL onto a particular handler method ¤  Example: the URL /webapp/sayHelloWorld is mapped to HelloWorldController.sayHelloWorld() @Controller public class HelloWorldController { @RequestMapping("/sayHelloWorld") public ModelAndView sayHelloWorld() { ... } } 46
  • Handler methods are unique endpoints ¤  Think of handler methods as unique endpoints, with mappings derived from @RequestMapping information @RequestMapping("/sayHelloWorld") public ModelAndView sayHelloWorld() {...} 47
  • Pro and cons of Annotation-based controllers ¤  The mapping is in the controller definition: ¤  Pro: when you open a controller, you can see which URLs the controller is mapped to ¤  Con: the mapping is scattered throughout the codebase, making it harder to see which URL is mapped to which handler method @RequestMapping("/sayHelloWorld") public ModelAndView sayHelloWorld() {...} 48
  • Mapping URLs to handlers ¤  In order to interpret the mappings defined in the controller class we need a HandlerMapping implementation @RequestMapping("/sayHelloWorld") public ModelAndView sayHelloWorld() {...} 49
  • HandlerMapping determines which handler to call ¤  The HandlerMapping interface provides the abstraction for mapping requests to handlers ¤  Each HandlerMapping implementation is able to inspect the request and come up with an appropriate handler (e.g., a Controller) Dispatcher Servlet Handler MappingHTTP Request HTTP Request Handler (e.g., Controller) 50
  • HandlerMapping determines which handler to call ¤  The DispatcherServlet consults one or more HandlerMapping implementations to know which handler can handle the request 51 Dispatcher Servlet Controller Handler Mapping ① ② ③
  • HandlerMapping determines which handler to call ¤  If no handler is found, an HTTP 404 response is send back to the client Dispatcher Servlet Controller Handler Mapping ① ② ③ Request 52
  • Override HandlerMapping special bean ¤  DefaultAnnotationHandlerMapping is the default HandlerMapping implementation ¤  Starting from Spring 3, the suggested implementation became RequestMappingHandlerMapping ¤  RequestMappingHandlerMapping is a HandlerMapping implementation that allows to perform more advanced operations (e.g., data validation) 53
  • Override HandlerMapping special bean ¤  To start using RequestMappingHandlerMapping, it is sufficient to alter [frontcontroller]-servlet.xml so as to add: <mvc:annotation-driven/> 54
  • The controller interacts with the service layer ¤  After being invoked, the controller processes the HTTP request and interacts with the service layer to perform whatever work is necessary Service layerController 55
  • The controller chooses the next view ¤  When processing is complete, the controller is responsible for building up the model and choosing what view the user sees next Service layerController Model 56
  • ModelAndView class ¤  The combination of Model and View is encapsulated in a class named ModelAndView ¤  By returning a ModelAndView object, the controller specifies both the Model and the View to render next @RequestMapping("/sayHelloWorld") public ModelAndView sayHelloWorld() {...} 57
  • Model and View are distinct entities ¤  Remember that Model and View are entirely distinct ¤  ModelAndView merely holds both to make it possible for a controller to return both in a single return value ¤  Later on we will see other returning strategies that do not involve the explicit usage of ModelAndView @RequestMapping("/sayHelloWorld") public ModelAndView sayHelloWorld() {...} 58
  • Controllers are unaware of the view technology ¤  Spring MVC makes a special effort to keep the controller unaware of any view technology used ¤  Therefore: ¤  the Model is a collection of arbitrary objects, and ¤  the View is specified with a logical name ¤  the special bean ViewResolver will later resolve the view’s logical name to an actual view instance 59
  • Costructing a ModelAndView ¤  QUI UN ESEMPIO DI CODICE CON IL MODEL INVENTATO @RequestMapping("/sayHelloWorld") public ModelAndView sayHelloWorld() { // put objects into the model MysteriousModelType model = new MysteriousModelType(); model.insert(usefulData); // set the view logical name String viewName = "sayHello"; // return the model and the view logical name ModelAndView mav = new ModelAndView(viewName, model); return mav; } Even if we still do not know the model data type… ..we know that it stores the data resulting from the user’s action The next view to render is specified by means of a logical name 60
  • The Model is the data needed by the view ¤  The Model the collection of named objects needed by the view so to that it can be rendered ¤  Example: Orders the user has placed Front Controller Controller Model View Model Service layer HTTP request 61
  • A model is a collection of model attributes ¤  Those named objects are usually called model attributes Front Controller Controller Model View Model Service layer HTTP request 62
  • The model is a map of objects ¤  The Model is purposely generic so that it may work with any view rendering technology ¤  Specifically, the Model is a map, allowing the use of multiple objects keyed by name <key1, value1> <key2, value2> <key3, value3> <key4, value4> Model 63
  • Possible Model implementations ¤  In practice, several data structures can be used for storing the Model attributes: ¤  An implementation of java.util.Map ¤  an Implementation of the Model interface provided by Spring ¤  A ModelMap object provided by Spring 64
  • Deciding could easily become difficult «interface» java.util.Map java.util.HashMap java.util.TreeMap java.util.LinkedHashMap «interface» org.springframework.ui.Model org.springframework.ui.ModelMap org.springframework.ui.ExtendedModelMaporg.springframework.ui.RedirectAttributeModelMap ModelMap does not implement the Model interface… …but its derived classes do implement the Model Interface ModelMap implements the Map interface 65
  • Deciding could easily become difficult «interface» java.util.Map java.util.HashMap java.util.TreeMap java.util.LinkedHashMap «interface» org.springframework.ui.Model org.springframework.ui.ModelMap org.springframework.ui.ExtendedModelMaporg.springframework.ui.RedirectAttributeModelMap Let’s try to sort this out :-) 66
  • Model as a Map ¤  The only requirement when using java.util.Map to store Model attributes is that the key has to be of type String ¤  Map<String, Object> is a popular choice Map<String, Object> model = new HashMap<String, Object>(); model.put("name", "John"); model.put("surname", "Smith"); 67
  • Model as a Map @RequestMapping("/sayHelloWorld") public ModelAndView sayHelloWorld() { // put objects into the model Map<String, Object> model = new HashMap<String, Object>(); model.put("name", "John"); model.put("surname", "Smith"); // set the view logical name String viewName = "sayHello"; // return the model and the view logical name ModelAndView mav = new ModelAndView(viewName, model); return mav; } 68
  • Model as input parameter ¤  Annotation-based controllers allow for very flexible method signatures ¤  For instance, it is common practice to let Spring provide the Model directly as an input parameter @RequestMapping("/sayHelloWorld") public ModelAndView sayHelloWorld(Map<String, Object> model){ ... } 69
  • Model as input parameter ¤  By doing so, Controller classes can be easily unit-tested* @Test public void testSayHelloWorld() { HelloWorldController controller = new HelloWorldController(); Map<String, Object> model = new HashMap<String, Object>(); ModelAndView modelAndView = controller.sayHelloWorld(model); // Test assertEquals("sayHello", modelAndView.getViewName()); assertNotNull(modelAndView.getModel().get("name")); } * Snippet adapted from http://stackoverflow.com/a/9363053/1849221 70
  • Many possible return values ¤  A handler method is not actually required to return a ModelAndView object ¤  Handler methods can have one of several different return values @RequestMapping("/sayHelloWorld") public String sayHelloWorld(Map<String, Object> model) { ... } Even if we are not returning a ModelAndView, this handler method signature is perfectly legit 71
  • Handler methods can return the name of the View ¤  The returned String is used as the logical name of the View to render @RequestMapping("/sayHelloWorld") public String sayHelloWorld(Map<String, Object> model) { ... } 72
  • Handler methods can return the name of the view ¤  By doing so, we do not need to explicitly declare a ModelAndView object @RequestMapping("/sayHelloWorld") public String sayHelloWorld(Map<String, Object> model) { // put objects into the model model.put("name", "John"); model.put("surname", "Smith"); // return the view logical name return "sayHello"; } 73
  • Model as a Model ¤  The downside of using a Map<String, ?> is that we have to decide the name of each model attribute we want to store Account account = ... List<SpecialDeal> specialDeals = ... // put objects into the model model.put("account", account); model.put("specialDeals", specialDeals); Deciding names…boring (and difficult) 74
  • Model as a Model ¤  The Model interface provides convenient methods for populating the Model, such as addAttribute() @RequestMapping("/specialDeals") public String listSpecialDeals(Model model) { // this comes from the service layer List<SpecialDeal> specialDeals = ... model.addAttribute(specialDeals); return "specialDeals/list"; } 75
  • Model as a Model ¤  The addAttribute() method does the same of the Map’s put() method, except that it automatically generates the name for the model attribute @RequestMapping("/specialDeals") public String listSpecialDeals(Model model) { // this comes from the service layer List<SpecialDeal> specialDeals = ... model.addAttribute(specialDeals); return "specialDeals/list"; } No name specified 76
  • Naming strategy ¤  The strategy for determining the name for an added object is as follows: ¤  Scalar object: take the the uncapitalized, unqualified class name ¤  Collection object: take the uncapitalized, unqualified class name of the first object in the collection, and use that with the List appended to the name ¤  Examples: ¤  com.myapp.Product becomes product ¤  List<com.myapp.Product> becomes productList 77
  • You can still decide the names ¤  However, if needed it is still possible to decide the name of each model attribute 78 @RequestMapping("/sayHelloWorld") public String sayHelloWorld(Model model) { // put objects into the model model.addAttribute("name", "John"); model.addAttribute("surname", "Smith"); // return the view logical name return "sayHello" } As both “John” and “Smith” are of types String, it is better to explicitly name them
  • Model as ModelMap ¤  the ModelMap class is a Map, but it provides some additional conveniences w.r.t. the plain Map interface ¤  Namely: ¤  It adheres to the same naming convention as Model ¤  The addAttribute() method checks if the values are null ¤  Supports chained calls of the addAtribute() method 79
  • Model as ModelMap ¤  Example: 80 @RequestMapping("/sayHelloWorld") public String sayHelloWorld(ModelMap model) { // put objects into the model model.addAttribute("name", "John") .addAttribute("surname", "Smith"); // return the view logical name return "sayHello" } Chained calls are handy
  • Writing Views
  • The View renders the model ¤  It is the View responsibility to intelligently render the objects in the Model 82 Front Controller ControllerModelView Model
  • The View interface ¤  Spring MVC does not make any assumption on the specific view technology ¤  To this end, views are modeled according to the View interface: 83 public interface View { void render(Map<String,?> model, HttpServletRequest request, HttpServletResponse response) String getContentType(); }
  • The View interface ¤  As for many Spring’s interfaces, the View interface is really simple: 84 public interface View { void render(Map<String,?> model, HttpServletRequest request, HttpServletResponse response) String getContentType(); }
  • The View’s render() method ¤  Specifically, the View interface exposes a render() method 85 void render(Map<String,?> model, HttpServletRequest request, HttpServletResponse response)
  • The View’s render() method ¤  The View will render (generate) the output starting from: ¤  the Model, ¤  the servlet’s request and response objects 86 void render(Map<String,?> model, HttpServletRequest request, HttpServletResponse response)
  • The View’s render() method ¤  The render() method returns void, i.e., this is the arriving point of the entire request processing pipeline* 87 void render(Map<String,?> model, HttpServletRequest request, HttpServletResponse response) * Here we are not considering possible calls to HandlerInterceptor.afterCompletion()
  • The View’s render() method ¤  That is, it is responsibility of the View not just to render the content, but to actually return it to the client 88 void render(Map<String,?> model, HttpServletRequest request, HttpServletResponse response)
  • Writing a View implementation ¤  Given how simple to View interface is, we can easily write a View implementation: 89 public class HelloWorldView implements View { public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { PrintWriter out = response.getWriter(); out.print("Hello, "); out.println(model.get("name") + " " + model.get("surname")); out.flush(); out.close(); } } Here we render the Model
  • Spring comes with many View implementations ¤  Most probably, we would prefer to use a specific view technology, rather than implementing our own Views ¤  Spring provides many View implementations: ¤  InternalResourceView (JSP) ¤  JSTLView (JSP + JSTL) ¤  VelocityView (Velocity) ¤  … 90
  • A View from a JSP page ¤  Example: we can easily obtain a View object starting from a JSP page 91 View view = new InternalResourceView("/WEB-INF/jsp/flightList.jsp");
  • The View object can be instantiated directly into the Controller ¤  We can easily create the View to render directly into the Controller class 92 @RequestMapping("/sayHelloWorld") public ModelAndView sayHelloWorld(Map<String, Object> model) { model.put("name", "John"); model.put("surname", "Smith"); View view = new InternalResourceView("/WEB-INF/jsp/ sayHello.jsp"); return new ModelAndView(view, model); } We explicitly say that the next View must be created starting from the sayHello.jsp JSP page
  • Returning the view logical name ¤  However, all handler methods that we previously defined return the logical name of the view, rather than the View object itself 93 @RequestMapping("/sayHelloWorld") public String sayHelloWorld(ModelMap model) { model.addAttribute("name", "John”); return "sayHello" }
  • Should we return the View or the view logical name? ¤  It turns out that the View can be specified either as a View implementation or as String representing the View logical name ¤  Now we have two competing approaches… 94 Which approach should we prefer among the two?
  • Prefer to return the logical name of a View ¤  We should always prefer returning the logical name of the View ¤  Upside: Controller and Views are completely decoupled, the Controller knows nothing of the View but its name 95 @RequestMapping("/sayHelloWorld") public String sayHelloWorld(ModelMap model) { ... return "sayHello" }
  • Resolving logical names to View objects ¤  The Controller delegates the choice to some other component that knows how to find the View starting from its logical name ¤  At first glance, it seems that DispatcherServlet will resolve the view logical name to the View object 96 Front Controller ControllerModelView Model
  • ViewResolver preforms the mapping ¤  The job actually falls to the ViewResolver special bean ¤  An implementation of ViewResolver is able to provide the mappings between View names and the View objects 97 Dispatcher Servlet ViewResolver ① ② ③ ControllerView
  • The ViewResolver interface ¤  As with View, ViewResolver is a really straightforward interface: 98 public interface ViewResolver { View resolveViewName(String viewName, Locale locale); }
  • ViewResolver implementations ¤  Spring MVC provides several ViewResolver implementations ¤  Examples: ¤  InternalResourceViewResolver ¤  BeanNameViewResolver ¤  VelocityViewResolver ¤  … 99
  • InternalResourceViewResolver ¤  The most commonly used view resolver when developing with JSP is the InternalResourceViewResolver ¤  InternalResourceViewResolver takes the logical name of the view and surrounds it with a prefix and a suffix 100 /WEB-INF/jsp/sayHello.jsp prefix logical name suffix
  • InternalResourceViewResolver ¤  We need to configure InteralResourceViewResolver in [frontcontroller]-servlet.xml 101 <bean class="org.springframework.web. servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean>
  • Hiding JSP pages ¤  It is good practice to place all view pages under the /WEB-INF directory ¤  This protects the pages from being retrieved independently of the Controllers that configure them ¤  Clients have no direct access the the content of the /WEB-INF folder 102
  • References 103
  • References ¤  Stackoverflow, Design patterns for web applications http://stackoverflow.com/a/3542297/1849221 ¤  SpringSource, Spring Framework Reference http://docs.spring.io/spring/docs/current/spring-framework- reference/pdf/spring-framework-reference.pdf ¤  Stackoverflow, ModelMap usage in Spring http://stackoverflow.com/questions/2902706/modelmap- usage-in-spring ¤  SpringSource, Java-doc APIs http://docs.spring.io/spring/docs/4.0.x/javadoc-api/ overview-tree.html 104
  • References ¤  S. Ladd, K. Donald, Expert Spring MVC and Web flows, Apress Publications ¤  M. Deinum, K. Serneels, Pro Spring MVC: with Web flows, Apress Publications ¤  Craig Walls, Spring in Action (3rd Edition), Manning Publications ¤  T. N. Husted, C. Dumoulin, G. Franciscus, D. Winterfeldt, Struts 1 In Action, Manning Publications 105
  • References ¤  Clarence Ho, Rob Harrop, Pro Spring 3, Apress Publications ¤  Rod Johnson et al., Professional Java Development with the Spring Framework, Wiley Publishing 106