What is the use of DispatcherServlet in Spring MVC? Interview Question

Hello guys, In today's article we are going to discuss one interesting and important Spring MVC concepts, which is also a popular Spring Interview question. How DispatcherServlet works internally in Spring MVC or What is the role of DispatcherServlet in Spring MVC is some of the frequently asked Spring MVC Interview Questions. You might have seen them already during your previous Java web development interviews but if you have not, it's a good question to know. In this article, I'll answer these questions by explaining What is DispatcherServlet and its importance in Spring MVC. The DispatcherServlet is one of the important components of the Spring MVC web framework and acts as a Front Controller.

Similar to other Java web framework like Struts 1.x and Struts 2.x, Spring MVC also uses a Front Controller (see Patterns of Enterprise Application Architecture)  to receive all incoming request and delegates to other components for further processing like Spring MVC controllers which are annotated using @Controller annotation and ViewResolvers like the InternalResourceViewResolver class.

A Front Controller is a common pattern in web application and used to receive request and delegate to other components in the application for actual processing. The DispatcherServlet is a front controller like it provides a single entry point for a client request to Spring MVC web application and forwards request to Spring MVC controllers for processing.

How does DispatcherServlet know that which request should be forwarded to which Controller? Well, Spring uses mapping handlers for that, which I will explain to you in the next section when we'll see how DispatcherServlet works internally.

Apart from being a front controller, DispatcherServlet also plays an important role in view resolution, error handling, locale resolution, theme resolution, etc. Btw, if you are not familiar with Spring in general and Spring MVC in particular, you should also join Spring Framework 5: Beginner to Guru course on Udemy, one of the most up-to-date courses on Spring framework and it also covers Spring 5.0.




How to configure DispatcherServlet in Spring?

The DispatcherServlet is like any other Servlet class and it has to be declared inside the deployment descriptor or web.xml file as shown below:

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>
          org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <!--Defaults to WEB-INF\dispatcher-servlet.xml -->
        <param-value>classpath:mvc-config.xml</param-value>
    </init-param>
</servlet> 

Its URL pattern is usually "*" so that all incoming request should go through Dispatcher servlet as shown below:

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

I haven't shown here but, DispatcherServlet is also usually preloaded using the load-on-startup tag of the deployment descriptor. You can give zero or positive value on this tag to pre-load a servlet, otherwise, the servlet will only be loaded when a request will arise.

If your servlet does a lot of job on initialization like DispatcherServlet which initializes all the beans declared in its web context like controllers, view resolvers, and mapping handlers then it could slow down the response time.


Btw, it's not the only way to declare DispatcherServlet in Spring MVC. From Spring 3.2 and Servlet 3.0 specification, you can programmatically declare DispatcherServlet using ServletContainerInitializer interface.

This is a Servlet 3,0 feature which allows Servlet 3.0 compliant containers like Tomcat 7 or higher to scan and load any class which implements this interface.

Spring provides an implementation of this interface as SpringServletContainerInitializer and a convenient class called AbstractAnnotationConfigDispatcherServletInitialzer in Spring 3.2 to configure DispatcherServlet without deployment descriptor.

This class implements SpringServletContainerInitializer hence automatically picked by Servlet 3.0 compliant containers. See Introduction to Spring MVC by Bryan Hansen on Pluralsight to know more about configuring DispatcherServlet using Java Configuration.

How DispatcherServlet of Spring MVC works internally



How Dispatcher Servlet works Internally in Spring?

As I said, DispatcherServlet wears many hats in Spring. It acts as a front controller and provides a single entry point for the application. It then uses handler mappings and handler adapters to map a request to the Spring MVC controllers. It uses @Controller and @RequestMapping annotation for that purpose.

Once the request is processed by the Spring MVC controller, it returns a logical view name instead of the view. Though, you can even configure Controler's handler methods to not return any View name by declaring return type as void.

You can even use @ResponseBody annotation in the case of REST to directly write the output to the HTTP response body. See REST with Spring course by Eugen to learn more about developing RESTful web services using Spring MVC.

When DispatherServlet receives view name, it consults the ViewResolver to find the right view. There is a chain of ViewResolver is maintained at the Spring MVC framework. They try to resolve the logical view name into a Physical resource like a JSP page or a FreeMaker or Velocity template.

The ViewResolver are invoked in order, if first in the chain not able to resolve the view then it returns null and next ViewResolver in the chain is consults.

Once the right view is found, DispatcherServlet forwards the request along with Model data to the View for rendering like a JSP page.

By default, DispatcherServlet uses InternalResourceViewResolver which uses prefix and suffix to convert a logical view name e.g. "home" to /WEB-INF/home.jsp. The View interface also has getContentType() method, which returns content type the view produces (JstlView has text/HTML). This is usually the default content type for requests handled by the dispatcher servlet in Spring. See Spring MVC for Beginners in 25 Steps to learn more about request handing in Spring MVC.

Here is a nice diagram which explains how DispatcherServlet works internally in Spring MVC

What is the use of DispatcherServlet in Spring MVC? Interview Question



In short, DispatcherServlet is used following things in Spring MVC:
  1. Receives all request as Front Controller  and provides a single entry point to the application
  2. Mapping requests to correct Spring MVC controller
  3. Consulting ViewResolvers to find correct View
  4. Forwarding request to chosen View for rendering
  5. Returning the response to the client
  6. Creates web-context to initialize the web-specific beans like controllers, view resolvers and handler mapping

That's all about what is the use of DispatcherServlet in Spring framework. It's is one of the key components of Spring MVC which is used to receive all incoming request and forward them to right controllers for actual processing. It finds the right controllers by using handler mappings like SimpleUrlHandlerMapping or BeanNameUrlHandlerMapping, which check if the bean name is the same as view name and the bean implements the View interface.

If you are using annotations then it can also use @Controller and @RequestMapping annotations to find the right controller to process a particular request. Once the request is processed by the controller it returns a logical view name to DispatcherServlet.

The DispatcherServlet then consults ViewResolver and LocalResolvers to find the right View to render the output. Once the correct View is chosen, it forwards the request to the View for rendering the response.

Further Reading
Spring Framework 5: Beginner to Guru
Spring Master Class - Beginner to Expert 
Spring MVC for Beginners in 25 Steps

Other Spring related articles you may like to explore this blog
  • How Spring MVC works internally? (answer)
  • Difference between @RestController and @Controller? (answer)
  • 15 Spring Boot Interview Questions for Java Developers (questions)
  • 3 ways to learn Spring Framework better (article)
  • Free Courses to learn Spring MVC and Spring Boot (courses)
  • How to enable Spring security in Java application? (answer)
  • Does Spring certification help in Job and Career? (article)
  • How to prepare for Spring Certification? (guide)
  • 3 Best Practices Java Developers Can learn from Spring (article)
  • Difference between @Autowired and @Injection annotations in Spring? (answer)
  • 5 Spring and Hibernate online courses for Java developers (list)
  • 5 Spring Boot courses for Java developers (courses)
  • 5 courses to learn Microservices with Spring Boot and Spring Cloud (courses)
Thanks for reading this article so far. If you like this interview question then please share with your friends and colleagues. If you have any question or suggestion then please drop a comment and I'll try to find an answer for you. 

P.S. - If you want to learn how to develop RESTful Web Services using Spring Framework, check out Eugen Paraschiv's REST with Spring course. He has recently launched the certification version of the course, which is full of exercises and examples to further cement the real world concepts you will learn from the course.

No comments:

Post a Comment