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 workflow
The above introduction acts as a top-level overview. Now, let’s see a bit more specifically how it happens behind the scenes.
- Sever request/s are arriving at the server and are received by the Dispatcher servlet.
- 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.
- There are 2 ways of defining a URL mapping:
- web.xml file
- controller’s methods annotations
- There are 2 ways of defining a URL mapping:
- One or many instances of HandlerInterceptor objects have been retrieved from the handler object.
- An instance of HandlerAdapter is retrieved from the handler object.
- Thanks to this instance, we can invoke the handle method which results in the execution of whatever logic the controller class has.
- The post-processing logic on the HandlerInterceptor instances have executed. This is the final step before the rendering method is invoked.
- The appropriate view component to be returned back to the response is done by a ViewResolver instance.
- 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.
<web-app> <servlet> <servlet-name>example</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>example</servlet-name> <url-pattern>*.form</url-pattern> </servlet-mapping> </web-app>
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.