How DispatcherServlet process a request in Spring MVC Application?

One of the common question in Spring MVC is, how does DispatcherServlet process a request in Spring MVC? or What is the role of DispatcherServlet in Spring MVC framework? This is an excellent question to any Java or Spring web developer, the answer to this question shows how much you know about Spring MVC framework and its working. Actually, DispatcherServlet plays a significant role in Spring MVC. It acts as a front controller, and all incoming request passes through it, of course, you can configure this in URL pattern of DispatcherServlet declaration in web.xml, but this is the case for many Spring based web application.

The job of DispatcherServlet is to find the right controller for processing the request and then when the handler method returns the logical view name, it also consults view resolvers to see the actual view. Once the real view is found, and output is rendered, it sends the response back to the client.

The DispatchServlet is an implementation of the front controller pattern (see Patterns of Enterprise Application Architecture), but it does more than that. It not only handles all request but it is also responsible for view resolution, locale resolution and theme resolution in Spring MVC framework, but the most important job of the DispatcherServlet is to finding the mapping handlers and routing the request to them. I'll explain that in the next paragraph.

Btw, if you have worked in Spring MVC then you should already have some basic ideas about things works, but if you don't have any prior experience and just started with Spring framework and Spring MVC then I suggest you to first go through a comprehensive course like Spring Framework 5: Beginner to Guru course on Udemy.  One of the most useful courses on Spring framework

How does DispatcherServlet process a request in Spring MVC?

As I said before, Dispatcher Servlet is used to handle all incoming requests and route them through different Spring Controllers for further processing, but how does it find which application needs to be routed to which controller or handlers?

To achieve this, DispatcherServlet uses HandlerMapping implementations. It can handle any implementation of HandlerMapping interface, like pre-built or customized implementations provided by the application to route incoming requests to handler objects.

By default, it uses BeanNameUrlHandlerMapping and DefaultAnnotationHandlerMapping, which is driven using @RequestMapping annotation.

In order to find the right methods for handling the request, it scans through all the classes declared using @Controller annotation and it also uses @RequestMapping annotation to find the types and methods responsible for handling requests.

1. The @RequestMapping annotation can map the request by path, for example @RequestMapping("/home"),

2. By HTTP method like
@RequestMapping("/home", method=RequestMethod.GET)

3. By request parameters like
@RequestMapping("/home", method=RequestMethod.POST, params="param1")

4. And, by presence of http request header like
@RequestMapping("/home", header="content-type=text/*"). 

You can also apply @RequestMapping annotation at the class level to filter incoming requests.

Though, you should remember that the @RequestMapping annotations will only be processed if a corresponding HandlerMapping (for type-level annotations) and/or HandlerAdapter (for method-level annotations) is present in the dispatcher servlet configuration file.

This is the case by default. However, if you are defining custom HandlerMappings or HandlerAdapters, then you need to make sure that a corresponding custom DefaultAnnotationHandlerMapping and/or AnnotationMethodHandlerAdapter is defined as well - provided that you intend to use @RequestMapping.

After processing the request, the Controller returns the logical view name and model to DispatcherServlet. It then consults to view resolvers to find the actual View to render the output. The view resolution strategy can be specified using a ViewResolver implementation, by default, DispatcherServlet uses InternalResourceViewResolver to convert logical view name to the actual View object like a JSP.

After this DispatcherServlet contacts the chosen view, like a JSP file with model data and it renders the output depending on the model data. This rendered output is returned to the client as a response.

Sometimes you don't even need a view like in the case of RESTful Web services. Their handler method directly writes into response using @ResponseBody annotation and DispatcherServlet return the answer to the client. See REST with Spring Certification class to learn more about developing and testing RESTful Web service using Spring MVC.

Also, in the Spring MVC framework, a web application can define any number of DispatcherServlet. Each servlet will operate in its own namespace, loading its own application context with mappings, handlers, etc. Only the root application context as loaded by ContextLoaderListener, if any, will be shared.

DispathcherServlet in Spring MVC

A picture is worth a thousand words, even a clumsy one like this which nicely summarise what happens when a request hit to spring container and how DispatcherServlet process a request in Spring MVC application:

How DispatcherServlet process a request in Spring MVC Application?

That's all about how DispatcherServlet process a web request in Spring MVC. As I said, it scans through all @Controler classes and @RequestMapping to find out all the handler methods and create a mapping of it. It then routes an incoming request to appropriate handlers, and when they return a logical view name, it uses ViewResolver implementations to resolve the name into a View object, which could be backed with any JSP or FreeMarker page.

The view then renders the response which is sent to the client by DispatcherServlet. In the case of RESTful Web Services and @RestController classes or handler methods annotated with @ResponseBody, the response is directly sent to the client as no view resolution happens.

Further Reading
Introduction to Spring MVC 4
REST with Spring
Spring Framework 5: Beginner to Guru
Spring in Action
How Spring MVC works?
Spring MVC Interview Questions

Thanks for reading this article so far. If you like this Spring MVC tutorial, then please share with your friends and colleagues. If you have any questions or feedback, then please drop a note.

No comments:

Post a Comment