Spring MVC, we need to declare the DispatcherServlet from the Spring MVC jar into web.xml. This Servlet listens for a URL pattern * as shown in below web.xml, which means all request is mapped to DispatcherServlet.

<web-app>
<!-- The front controller of this Spring Web application, responsible 
for handling all application requests -->
<servlet>
   <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/config/web-application-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
   <servlet-name>example</servlet-name>
   <url-pattern>*</url-pattern>
</servlet-mapping>
</web-app>

The URL pattern is important, if the request matches the URL pattern of DispatcherServlet then it will be processed by Spring MVC otherwise not. The DispatcherServlet passes the request to a specific controller depending on the URL requested.

How does DispatcherServlet know which request needs to be passed to which controller?

Well, it uses the @RequestMapping annotation or Spring MVC configuration file to find out the mapping of the request URL to different controllers. It can also use specific request processing annotations like @GetMapping or @PostMapping. Controller classes are also identified using @Controller and @RestController (in the case of RESTful Web Services) annotations.

After processing the request, the Controller returns a logical view name and model to DispatcherServlet and it consults view resolvers(like Thymeleaf, Freemarker, JSP) until an actual View is determined to render the output. DispatcherServlet then contacts the chosen view e.g. Freemarker or JSP with model data and it renders the output depending on the model data.

This Rendered output is returned to the client as an HTTP response. On its way back it can pass to any configured Filter as well like Spring Security filter chain or Filters configured to convert the response to JSON or XML.

The DispatcherServlet from Spring MVC framework is an implementation of Front Controller Pattern and it's also a single point of entry - handle all incoming requests, but again that depends upon your URL pattern mapping and your application.

Untitled

The flow of the RESTful Web Service request is also not very different from this. It follows the same path but in the case of REST, the Controller methods are annotated with @ResponseBody which means it doesn't return a logical view name to DispatcherServlet, instead it write the output directly to the HTTP response body.