How servlet works, using Spring Dispatcher Servlet as an example

A Servlet is just like a CGI, it accept request and do some logic and return a response. Every application need at least one Servlet, and when the url pattern is matched, the servlet is called with request object passed in, the Servlet can be provided by you or by the framework you use.

In Spring Framework, one Servlet called dispatcher servlet is used to handle all requests. Its provided by Spring Framework, but you need to configure it , to tell the container to create and init the Servlet for you.

A typical Spring Dispatcher Servlet


Or the annotation version

        AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
        ServletRegistration.Dynamic dispatcher;
        dispatcher = servletContext.addServlet(DISPATCHER_SERVLET_NAME, new DispatcherServlet(dispatcherContext));

The dispatcher servlet is just a normal servlet, just like any other servlet, it extends HttpServlet , it must be declared in web.xml, but it also a bean, managed by Spring framework, so it connects the container and the spring context.

When dispatcher servlet get the request, it first looking for controller by the URL pattern, and then call the controller method, the method returns a logical view name and optioanlly a model populated with data. Then the actual view file is resolved by view resolver, the data in model are filled in the view file, the HTML response then is sent back to client.