In Chapter 2, Spring MVC Architecture – Architecting Your Web Store you saw the overall architecture of a Spring MVC application. We didn't go into any of the concepts in depth; our aim was for you to understand the overall flow.
In Spring MVC, the concept of Controllers has an important role, so we are going to look at Controllers in-depth in this chapter. This chapter will cover concepts such as:
In Spring MVC, the Controller's methods are the final destination point that a web request can reach. After being invoked, the Controller's method starts to process the web request by interacting with the Service layer to complete whatever work needs to be done. Usually, the Service layer executes business operations on domain objects and calls the Persistence layer to update the domain objects. After the processing is completed by the Service layer object, the Controller is responsible for updating and building up the model
object and chooses a View for the user to see next as a response.
Remember that Spring MVC always keeps the Controllers unaware of any View technology used. That's why the Controller returns only the logical View name, and later DispatcherServlet
consults with ViewResolver
to find out the exact View to render. According to the Controller, the Model is a collection of arbitrary Java objects and the View is identified by a logical View name. Rendering the correct View for the given logical View name is the responsibility of ViewResolver
.
In all our previous exercises, Controllers are used to return the logical View name and the Model is updated via the model
parameter available in the controller method. There is another, seldom used way of updating the model
parameter and returning the View name from the controller
parameter with the help of the ModelAndView
(org.springframework.web.servlet.ModelAndView
) object. Look at the following code snippets as an example:
@RequestMapping("/all") public ModelAndView allProducts() { ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("products", productService.getAllProducts()); modelAndView.setViewName("products"); return modelAndView; }
This code snippet just shows you how to encapsulate the Model and View using the modelAndView
object.