Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Thursday, March 23, 2023

What is the use of DispatcherServlet in Spring MVC Framework?

If you have worked with Spring MVC then you should know what is a DispatcherServlet? It's actually the heart of Spring MVC, precisely the C of MVC design pattern or Controller. Every single web request which is supposed to be processed by Spring MVC goes through DispatcherServlet. In general, its an implementation of Front Controller Pattern which provides a single point of entry in your application. It handles all incoming requests. It is also the bridge between Java and Spring. Btw, the DispatcherServlet is like any other Servlet is declared in the web.xml with a URL pattern but the only special thing is that the URL pattern for dispatcher servlet is enough to map every single web request to DispathcherServlert.

It is responsible for request handling by delegating requests to additional components of Spring MVC e.g. actual controller classes i.e. those which are annotated using @Controller or @RestController (in case of RESTful Web Services), Views, View Resolvers, handler mappers, etc.

Though the job of actual request mapping is done by @RequestMapping annotation, it's actually the DispatcherServlet which delegates request to the corresponding controller.

In the case of RESTful web services, it is also responsible for finding the correct message converter to convert the response into the format client is expecting like JSON, XML, or TEXT.

For example, if a client is expecting JSON then it will use the MappingJacksonHttpMessageConverter or MappingJackson2HttpMessageConverter (depending upon whether Jackson 1 or Jackson 2 is available in Classpath) to convert the response returned by convert into a JSON string.

You can further see Spring Framework 5: Beginner to Guru to learn more about developing RESTful web services using Spring 4 and Spring 5.

How does DispatcherServlet process request in Spring MVC

As I said before, Dispatcher Servlet is used to handle all incoming requests s and route them through different Spring Controllers for further processing. To achieve this, it determines which controllers should handle the incoming request.

The DispatcherServlet uses HandlerMapping implementations - pre-built or provided as part of the application to route incoming requests to handler objects. By default, it uses BeanNameUrlHandlerMapping and DefaultAnnotationHandlerMapping, which is driven by @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.

The @RequestMapping annotation can map the request

  1. by path like @RequestMapping(“path”), 
  2. by HTTP method like @RequestMapping("path", method=RequestMethod.GET)
  3. by request parameters like @RequestMapping("path"”, method=RequestMethod.POST, params="param1")
  4. and by the presence of HTTP request header like @RequestMapping("path", header="content-type=text/*").

You can also apply @RequestMapping annotation at the class level to filter incoming requests. If you are interested, you can further check Spring Framework 5: Beginner to Guru course on Udemy to learn the full range of options you can use with the @RequestMapping annotation. I'll also write an article about that but till then this course is one of the best resources.

What is the Use of DispatcherServlet in Spring MVC Framework?

Anyway, after processing the request 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 actual View object like a JSP.

After this DispatcherServlet contacts the chosen view e.g. 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 e.g. in case of RESTful Web services.

Their handler method directly writes into response using @ResponseBody annotation and DispatcherServlet directly returns a response to the client. See REST with Spring course to learn more about developing and testing RESTful Web service using Spring MVC.

what is the use of DispatcherServlet in Spring 5

10 Points about DispatcherServlet

In this article, I am going to share some of the useful and essential things about DispatcherServlet a Java Web Developer should know. These points will not only help you to understand the job of DispatcherServlet in Spring MVC better but also encourage you to learn more about them by exploring and researching each point.

1) The DispatcherServlet is the main controller of the Spring MVC Application. All incoming web request passes through DispatcherServlet before processed by individual Spring controllers i.e classes annotated using @Controller annotation.

2) The DispatcherServlet of Spring MVC is an Implementation of Front Controller Pattern (see Introduction to Spring MVC 4). A Front Controller is nothing but a controller that handles all requests for a website. They are often used in Web applications to implement workflows.

DispatcherServlet of Spring MVC - 10 things Java Developer should know

3) Like any other Servlet, DispatcherServlet of Spring MVC framework is also declared and configured in web.xml file as shown below:





4) The DispatcherServlet is an actual Servlet, it inherits from the HttpServlet base class. Servlet engine like Tomcat create an instance of this class and calls it various life-cycle methods e.g. init(), service() and destroy().

5) The DispatcherServlet provides a Single point of entry for your Spring MVC web application. As I said before, it handles all incoming requests.  See how Spring MVC works internally for more details of the inner workings of Spring.

6) Spring's DispatcherServlet is also completely integrated with the Spring IoC container and as such allows you to use every feature of the Spring framework like dependency injection.

7) The dispatcher servlet is configured as load-on-startup = 1 which means this Servlet should be created by Servlet container when you deploy the application rather than creating when a request arrived for this request.

This is done to reduce the response time of the first request because DispatcherServlet does a lot of job at the startup to scan and find all controllers and request mappings. See the Java Web Fundamentals course on Pluralsight by Kevin Jones to learn more about load-on-startup and other servlet fundamentals.

8) During initialization of DispatcherServlet, the Spring MVC framework will look for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and create the beans defined there e.g. if servlet name is "SpringMVC" as shown in the above web.xml configuration then it will look for a file named SpringMVC-Servlet.xml.

It also overrides the definitions of any beans defined with the same name in the global scope. You can change the exact location of this configuration file by using contextConfigLocation servlet initialization parameter.

DispatcherServlet of Spring MVC

9) In the Spring MVC framework, each DispatcherServlet has its own WebApplicationContext (see Spring in Action), which inherits all the beans already defined in the root WebApplicationContext. These inherited beans can be overridden in the servlet-specific scope, and new scope-specific beans can be defined locally to a given servlet instance.

10) The DispatcherServlet of Spring MVC framework can also return the last-modification-date, as specified by the Servlet API. It determines the last modification date by looking for an appropriate handler mapping and test if the handler that is found implements the LastModified interface. If yes, then it calls the getLastModified(request) method of the LastModified interface, and value is returned to the client.

That's all about the DispatcherServlet of Spring MVC framework. As I said, the DispatcherServlet is the backbone of Spring MVC and serves as the main controller which routes different HTTP requests to corresponding Spring Controllers. It is an implementation of the Front Controller design pattern and provides a single entry point to your Spring web application.

You configure DispatcherServlet in the web.xml but gives it load-on-startup value 1 to suggest container to load this Servlet during startup and not when a request comes up. This reduces response time for the first request.

Further Learning
Spring Master Class - Beginner to Expert
Spring Framework 5: Beginner to Guru
REST with Spring by Baeldung

Other Spring related articles you may like to explore
  • Difference between @RestControler and @Controller in Spring MVC? (answer)
  • 10 free courses to learn Spring Framework (courses)
  • 23 Spring MVC Interview questions for 2 to 3 years experienced (list)
  • 10 free courses to learn Spring Boot for beginners (courses)
  • What is the use of DispatcherServlet in Spring MVC? (answer)
  • 10 Courses to learn Microservices with Spring in Java (courses)
  • How to enable Spring security in Java application? (answer)
  • 5 Books and Courses to learn RESTful Web Services in Java (courses)
  • Does Spring certification help in Job and Career? (article)
  • 20 Spring Boot Interview Questions for Java developers (questions)
  • How to Crack the Spring Professional Certification (guide
  • 10 Frameworks for  full-stack Java developers (frameworks)
  • Top 5 Spring Certification Mock Exams (list)
  • Top 5 Courses to become full-stack JAva developers (courses)
  • Difference between @Autowired and @Injection annotations in Spring? (answer)
  • 5 Spring and Hibernate online courses for Java developers (list)
Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions, suggestions, or feedback or you have any point about dispatcher servlet which is not mentioned here but worth knowing then please drop a comment and I'll include it in the main article.

P. S. - If you don't mind learning from free resources then you can also check out my list of  Free Spring Core and Spring Boot courses for Java developers to start your journey. The list contains free online courses to learn Spring Core, Spring MVC, and Spring Boot. 

No comments :

Post a Comment