Dispatcher servlet in Spring

The dispatcher servlet is the most important component in the Spring Web MVC.


Why is the dispatcher servlet the most important component though? Because it acts as a glue, meaning it receives an incoming URL and finds the correct methods and views. It receives the URL via HTTP request. You can also think of it as a middleware, as it communicates with two ends – the sender of HTTP request and the Spring application. The Dispatcher servlet is completely integrated in the IoC container and allows you to use all features that Spring has.

Dispatcher Servlet example

Dispatcher servlet workflow

The above introduction acts as a top-level overview. Now, let’s see a bit more specifically how it happens behind the scenes.

  1. Sever request/s are arriving at the server and are received by the Dispatcher servlet.
  2. The Dispatcher servlet is granted a handler object which in most cases it will be an instance of HandlerExecutionChain which is from the HandlerMapping object which is based on the URL mapping.
    1. There are 2 ways of defining a URL mapping:
      1. web.xml file
      2. controller’s methods annotations
  3. One or many instances of HandlerInterceptor objects have been retrieved from the handler object.
  4. An instance of HandlerAdapter is retrieved from the handler object.
    1. Thanks to this instance, we can invoke the handle method which results in the execution of whatever logic the controller class has.
  5. The post-processing logic on the HandlerInterceptor instances have executed. This is the final step before the rendering method is invoked.
  6. The appropriate view component to be returned back to the response is done by a ViewResolver instance.
  7. The render method has finally been invoked on the instance of that view.

The Dispatcher Servlet inherits from HttpServlet and is declared in the web.xml file of your web application. Again, if you read Step 2 from above, you will see that we need URL mapping. First off, a URL mapping maps requests to the Dispatcher Handler to handle. Now, one way of using a URL mapping is by having it stored in the same web.xml file.





This code snippet example is taken from the Spring docs.

The example snippet shows that all requests that end with .form will be handled by the example Dispatcher servlet.

When a Dispatcher servlet has been initialized, the framework looks for file which name is [servlet-name]-servlet.xml in the web-inf directory of the application and creates the beans there and overrides all the definitions of the beans that were defined in the same name in a global scope.

0 0 votes
Article Rating
Inline Feedbacks
View all comments