What is the DispatcherServlet in Spring and its uses?

DispatcherServlet:

The Heart of Spring Web MVC

  •  A “front controller
    • coordinates all request handling activities
    • analogous to Struts ActionServlet / JSF FacesServlet
  • Delegates to Web infrastructure beans
  • Invokes user Web components
  • Fully customizable
    • interfaces for all infrastructure beans
    • many extension points

 

What is the DispatcherServlet in Spring

In Spring MVC framework Dispatcher Servlet access Front Controller which handles all coming requests and queues for forwarding to the different controller. The front controller is a typical design pattern in the web applications development. In this case, a single servlet receives all requests and transfers them to all other components of the application. The task of the DispatcherServlet is sent a request to the specific Spring MVC controller.

DispatcherServlet is responsible for initializing the WebApplicationContext and it loads all configuration related to the web components like controllers, view resolver, interceptors etc., It will be loaded and initialized by calling init() method init() of DispatcherServlet will try to identify the Spring Configuration Document with naming conventions like “servlet_name-servlet.xml” then all beans can be identify.

DispatcherServlet in Spring MVC

public class DispatcherServlet extends HttpServlet {

    ApplicationContext ctx = null;

    public void init(ServletConfig cfg){
        // 1. try to get the spring configuration document with default naming conventions
        String xml = "servlet_name" + "-servlet.xml";

        //if it was found then creates the ApplicationContext object
        ctx = new XmlWebApplicationContext(xml);
    }
    ...
}

 

What is used of DispatcherServlet in Spring
  1. DispatcherServlet capture request URI
  2. and hand over to HandlerMapping.
  3. HandlerMapping search mapping bean with a method of the controller, where the controller returning the logical name(view).
  4. Then this logical name is sent to DispatcherServlet by HandlerMapping.
  5. Then DispatcherServlet tells ViewResolver to give the full location of view by appending prefix and suffix, then DispatcherServlet gives view to the client.

 

Spring MVC Related Posts

 

Previous
Next

2 Comments

  1. ravi October 13, 2018
  2. Dinesh Rajput October 14, 2018