Friday, September 22, 2017

DispatcherServlet of Spring MVC - 10 things Java Developer should know

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, its 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 and DispatcherServlet like any other Servlet is declared in the web.xml with a URL pattern 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 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 e.g. 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. See REST with Spring by Baeldung to learn more about developing RESTful web services using Spring 3 and Spring 4.

How does DispatcherServlet process request in Spring MVC

As I said before, Dispatcher Servlet is used to handle all incoming requests 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 using @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. @RequestMapping annotation can map the request by path e.g. @RequestMapping(“path”), by HTTP method e.g. @RequestMapping("path", method=RequestMethod.GET), by request parameters e.g. @RequestMapping("path"”, method=RequestMethod.POST, params="param1") and by presence of HTTP request header e.g.
@RequestMapping("path", header="content-type=text/*"). You can also apply @RequestMapping annotation at the class level to filter incoming requests.

After processing the request Controller returns 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 e.g. 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 case of RESTful Web services.

Their handler method directly writes into response using @ResponseBody annotation and DispatcherServlet directly return a response to the client. See REST with Spring course to learn more about developing and testing RESTful Web service using Spring MVC.

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 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 (see Introduction to Spring MVC 4). 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.

DispatcherServlet of Spring MVC - 10 things Java Developer should know

3) Like any other Servlet, DispatcherServlet of Spring MVC framework is also declared and configured in web.xml file as shown below:





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.  See how Spring MVC works internally for more details of the inner workings of Spring.

6) Spring's DispatcherServlet is also completely integrated with the Spring IoC container and as such allows you to use every feature of Spring framework e.g. 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. See Java Web Fundamentals By Kevin Jones to learn more about load-on-startup and other servlet fundamentals.

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.

DispatcherServlet of Spring MVC

9) In the Spring MVC framework, each DispatcherServlet has its own WebApplicationContext (see Spring in Action), 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.

That's all about DispatcherServlet of Spring MVC framework. As I said, the DispatcherServlet is the backbone of Spring MVC and serves as the main controller which routes different HTTP request to corresponding Spring Controllers. It is an implementation of Front Controller design pattern and provides a single entry point to your Spring web application. 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.

Further Learning
Introduction to Spring MVC 4
REST with Spring by Baeldung
Spring Fundamentals by Bryan Hassen

Other Spring related articles you may like to explore
  • Difference between @RestControler and @Controller in Spring MVC? (answer)
  • 23 Spring MVC Interview questions for 2 to 3 years experienced (list)
  • What is the use of DispatcherServlet in Spring MVC? (answer)
  • How to enable Spring security in Java application? (answer)
  • Does Spring certification help in Job and Career? (article)
  • Top 5 Spring Certification Mock Exams (list)
  • Spring Fundamentals by Pluralsight (see)
  • Difference between @Autowired and @Injection annotations in Spring? (answer)
  • 5 Spring and Hibernate online courses for Java developers (list)

Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any question, suggestion, or feedback or you have any point about DispatcherServlert which is not mentioned here but worth knowing then please drop a comment and I'll include it in the main article.

No comments :

Post a Comment