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

How DispatcherServlet works internally in Spring MVC or What is the role of DispatcherServlet in Spring is some of the frequently asked Spring MVC Interview Question. You might have seen them already during your Java web development interview. In this article, I'll answer these question by explaining What is DispatcherServlet and its importance in Spring MVC. The DispatcherServlet is one of the important components of Spring MVC web framework and acts as a Front Controller. Similar to other Java web framework, Spring MVC also uses a front controller to receive all incoming request and delegates to other components for further processing e.g. Spring MVC controllers which are annotated using @Controller annotation and ViewResolvers e.g InternalResourceViewResolver class.

A Front Controller (see Patterns of Enterprise Application Architecture) 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 e.g. 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 you in 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.




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 e.g. DispatcherServlet which initializes all the beans declared in its web context e.g. 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  e.g. 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 Spring in Action 4th Edition to know more about configuring DispatcherServlet using Java Configuration.

How DispatcherServlet of Spring MVC works internally



How dispatcher servlet works internally?

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 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 Spring MVC framework. They try to resolve the logical view name into a Physical resource e.g. a JSP page or a FreeMaker or Velocity template.

The ViewResolver are invoked in an 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 e.g. 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.

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
- receives all request as Front Controller  and provides a single entry point to the application
- mapping requests to correct Spring MVC controller
- Consulting ViewResolvers to find correct View
- forwarding request to chosen View for rendering
- returning the response to the client
- creates web-context to initialize the web specific beans e.g. 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 e.g. SimpleUrlHandlerMapping or BeanNameUrlHandlerMapping, which check if the bean name is 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 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 Learning
Introduction to Spring MVC
Spring Security Fundamentals
How to Create Your First Spring Boot Application
Spring MVC books and resources
Spring Web Application Developer Certification

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