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
<servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
Or the annotation version
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext(); dispatcherContext.register(WebConfig.class); ServletRegistration.Dynamic dispatcher; dispatcher = servletContext.addServlet(DISPATCHER_SERVLET_NAME, new DispatcherServlet(dispatcherContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/");
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.