Spring MVC and Web Layer
August 7, 2021

M05 Q02 What is the DispatcherServlet and what is it used for?

DispatcherServlet is an internal Spring MVC component that implements HttpServlet from Java Servlet API and Front Controller Design Pattern. It is used to handle all requests to the application, based on servlet mapping, delegate those requests to controllers and produce response based on identified view.

DispatcherServlet has following responsibilities:

  • Delegates received requests to Controllers
  • Uses View Resolvers to resolve views pointed out by Controllers
  • Produces Response that is sent to user
  • Handles shared concerns, like exception mapping, error handling, security etc.

Front Controller Design Pattern allows you to implement shared algorithm for entire application responsible for request processing and handling shared concerns

Let's have a look what is the request lifecycle in this pattern. The user is usually a source of the request. Whenever the user is making the request against the server the Front Controller will handle all requests. I the case of Spring MVC the DispatcherServlet is a Front Controller.

The Front Controller does not complete all of the actions on its own. Instead, it delegates responsibilities to other components.

First, it searches the controller based on URI that can handle the request that was made. The Controller is expected to return the Model. Also, it is expected from the controller to return the view that should be used for rendering.

After the model was sent back to the Front Controller, it delegates responsibility for rendering to the View. It searches for an appropriate view. Once it is identified it is being used to render the data in the model. The model at this stage consists of attributes of the model and each attribute is data to be displayed.

And after when data have been rendered the response is being presented to the user.

Java Servlet

Servlet is a Java Technology used to create Web Applications on Java Platform with the usage of Application Servers. It is a set of interfaces, classes and documentation allowing you to extend capabilities of Application Servers. Servlet is protocol independent, however usually it is used to process HTTP Requests with usage of custom implementation of HttpServlet class. Servlet can be registered via web.xml, or programmatically via annotations since Servlet 3. Servlet registration requires url-patterns which informs application server which requests should be mapped to your servlet.