How does HTTP Request is handled in Spring MVC? DispatcherServlet Example Tutorial

One of the common interview questions in Spring MVC is, how does the DispatcherServlet process a request in Spring MVC? or What is the role of DispatcherServlet in the Spring MVC framework? This is an excellent question for any Java or Spring web developer because it exposed the candidate's knowledge about Spring MVC architecture and how its main components like Model, View, and Controller.   The answers to this question show how much you know about the 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 Spring Boot Interview Guide), but it does more than that. It not only handles all, requests but is also responsible for view resolution, locale resolution, and theme resolution in the 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. Still, if you don't have any prior experience and just started with Spring framework and Spring MVC, then I suggest you first go through a comprehensive course like Spring Framework 5: Beginner to Guru course on Udemy.  One of the most useful courses on the Spring framework





How does DispatcherServlet process an HTTP 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 the 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 the @RequestMapping annotation.

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 see 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 the 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. If you want to learn more about @RequestMapping and other Spring MVC annotations, I also suggest you check out Spring MVC for Beginners: Build Java Web Apps in 25 steps course on Udemy by Ranga Rao Karnam. It's one of the better courses to learn Spring MVC with a hands-on example.

Spring MVC Architecture explanation


However, 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.

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.

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 returns the answer to the client. See REST with Spring Certification class to learn more about developing and testing RESTful Web service using Spring MVC.




HTTP Request Flow and DispathcherServlet in Spring MVC

A picture is worth a thousand words, even a clumsy one like this which nicely summaries what happens when a request hit to spring container and how DispatcherServlet process a request in the 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.

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.


Other Java and Spring Articles you may like
  • 15 Spring Boot Interview Questions for Java Developers (questions)
  • Top 5 Courses to Learn and Master Spring Cloud (courses)
  • 5 Free Courses to Learn Spring Framework (free courses)
  • 5 Courses to Learn Spring Security (courses)
  • 10 Spring MVC annotations Java developer should learn (annotations)
  • Top 5 Spring Cloud annotations Java programmer should learn (cloud)
  • Top 5 Spring Boot Annotations Java Developers should know (read)
  • Top 5 Courses to learn Microservices in Java (courses)
  • @SpringBootApplication vs @EnableAutoConfiguration? (answer)
  • 5 Spring Books Experienced Java Developer Should Read (books)
  • Top 5 Frameworks Java Developer Should Know (frameworks)
  • 10 Advanced Spring Boot Courses for Java developers (courses)
  • 5 Courses to learn Spring Cloud for Beginners (courses)
  • 10 Free Spring Boot Courses for Java Developers (courses)
  • 10 Courses to learn Spring Security and OAuth2 (courses)

Thanks a lot for reading this article so far. If you like this Spring MVC tutorial and explanation of how Spring MVC process an HTTP request and what role Dispatcher Servlet plays then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you want to learn the Spring framework from scratch and looking for some free resources then you can also check out this list of free courses to learn Core Spring and Spring Boot online. It contains some free courses from Udemy, Pluralsight, and other online platforms.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.