Use of DispatcherServlet in Spring MVC Framework
If you have worked with Spring MVC then you should know what is a DispatcherServlet? It's actually the heart of Spring MVC, precisely the C of MVC design pattern or Controller. Every single web request which is supposed to be processed by Spring MVC goes through DispatcherServlet. In general, it's an implementation of Front Controller Pattern which provides a single point of entry in your application. It handles all incoming requests. It is also the bridge between Java and Spring. Btw, the DispatcherServlet is like any other Servlet is declared in the web.xml with a URL pattern but the only special thing is that the URL pattern for dispatcher servlet is enough to map every single web request to DispathcherServlert.
It is responsible for request handling by delegating requests to additional components of Spring MVC e.g. actual controller classes i.e. those which are annotated using @Controller or @RestController (in case of RESTful Web Services), Views, View Resolvers, handler mappers, etc.
Though the job of actual request mapping is done by @RequestMapping annotation, it's actually the DispatcherServlet which delegates request to the corresponding controller.
In the case of RESTful web services, it is also responsible for finding the correct message converter to convert the response into the format client is expecting like JSON, XML, or TEXT.
For example, if a client is expecting JSON then it will use the MappingJacksonHttpMessageConverter or MappingJackson2HttpMessageConverter (depending upon whether Jackson 1 or Jackson 2 is available in Classpath) to convert the response returned by convert into a JSON string.
How does DispatcherServlet process request in Spring MVC
As I said before, Dispatcher Servlet is used to handle all incoming requests s and route them through different Spring Controllers for further processing. To achieve this, it determines which controllers should handle the incoming request.
The DispatcherServlet uses HandlerMapping implementations - pre-built or provided as part of the application to route incoming requests to handler objects. By default, it uses BeanNameUrlHandlerMapping and DefaultAnnotationHandlerMapping, which is driven by @RequestMapping annotation.
In order to find the right methods for handling the request, it scans through all the classes declared using @Controller annotation and it also uses @RequestMapping annotation to find the types and methods responsible for handling requests.
The @RequestMapping annotation can map the request
- by path like @RequestMapping(“path”),
- by HTTP method like @RequestMapping("path", method=RequestMethod.GET),
- by request parameters like @RequestMapping("path"”, method=RequestMethod.POST, params="param1")
- and by the presence of HTTP request header like @RequestMapping("path", header="content-type=text/*").
You can also apply @RequestMapping annotation at the class level to filter incoming requests.
Anyway, after processing the request Controller returns the logical view name and model to DispatcherServlet. It then consults to view resolvers to find the actual View to render the output.
The view resolution strategy can be specified using a ViewResolver implementation, by default, DispatcherServlet uses InternalResourceViewResolver to convert logical view name to actual View object like a JSP.
After this DispatcherServlet contacts the chosen view e.g. a JSP file with model data and it renders the output depending on the model data. This rendered output is returned to the client as a response. Sometimes you don't even need a view e.g. in the case of RESTful Web services.
Their handler method directly writes into response using @ResponseBody annotation and DispatcherServlet directly returns a response to the client.
10 Points about DispatcherServlet
In this article, I am going to share some of the useful and essential things about DispatcherServlet a Java Web Developer should know. These points will not only help you to understand the job of DispatcherServlet in Spring MVC better but also encourage you to learn more about them by exploring and researching each point.
1) The DispatcherServlet is the main controller of the Spring MVC Application. All incoming web request passes through DispatcherServlet before processed by individual Spring controllers i.e classes annotated using @Controller annotation.
2) The DispatcherServlet of Spring MVC is an Implementation of Front Controller Pattern. A Front Controller is nothing but a controller that handles all requests for a website. They are often used in Web applications to implement workflows.
3) Like any other Servlet, DispatcherServlet of Spring MVC framework is also declared and configured in the web.xml file as shown below:
<web-app>
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>*</url-pattern>
</servlet-mapping>
</web-app>
4) The DispatcherServlet is an actual Servlet, it inherits from the HttpServlet base class. Servlet engine like Tomcat create an instance of this class and calls it various life-cycle methods e.g. init(), service(), and destroy().
5) The DispatcherServlet provides a Single point of entry for your Spring MVC web application. As I said before, it handles all incoming requests.
6) Spring's DispatcherServlet is also completely integrated with the Spring IoC container and as such allows you to use every feature of the Spring framework like dependency injection.
7) The dispatcher servlet is configured as load-on-startup = 1 which means this Servlet should be created by Servlet container when you deploy the application rather than creating when a request arrived for this request.
This is done to reduce the response time of the first request because DispatcherServlet does a lot of job at the startup to scan and find all controllers and request mappings.
8) During initialization of DispatcherServlet, the Spring MVC framework will look for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and create the beans defined there e.g. if servlet name is "SpringMVC" as shown in the above web.xml configuration then it will look for a file named SpringMVC-Servlet.xml.
It also overrides the definitions of any beans defined with the same name in the global scope. You can change the exact location of this configuration file by using contextConfigLocation servlet initialization parameter.
9) In the Spring MVC framework, each DispatcherServlet has its own WebApplicationContext , which inherits all the beans already defined in the root WebApplicationContext. These inherited beans can be overridden in the servlet-specific scope, and new scope-specific beans can be defined locally to a given servlet instance.
10) The DispatcherServlet of Spring MVC framework can also return the last-modification-date, as specified by the Servlet API. It determines the last modification date by looking for an appropriate handler mapping and test if the handler that is found implements the LastModified interface. If yes, then it calls the getLastModified(request) method of the LastModified interface, and value is returned to the client.
You configure DispatcherServlet in the web.xml but gives it load-on-startup value 1 to suggest container to load this Servlet during startup and not when a request comes up. This reduces response time for the first request.
Comments
Post a Comment