dineshonjava

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 forward to the different controller. 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 to all other components of the application. The task of the DispatcherServlet is send request to the specific Spring MVC controller.

DispatcherServlet is responsible for initialize 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.


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 method of controller, where controller returning logical name(view).
  4. Then this logical name is send to DispatcherServlet by HandlerMapping.
  5. Then DispatcherServlet tell ViewResolver to give full location of view by appending prefix and suffix, then DispatcherServlet give view to the client.