How Spring MVC Framework works? How HTTP Request is processed?
One of the frequently asked Spring MVC Interview questions is about explaining the flow of web request i.e. how an HTTP request is processed from start to end. In other words, explaining the flow of request in Spring MVC. Since many of my readers ask this question time and again, I thought to summarize the flow of request processing in a short article. It all starts with the client, which sends a request to a specific URL. When that request hit the web container e.g. Tomcat it look into web.xml and find the Servlet or Filter which is mapped to that particular URL. It the delegate that Servlet or Filter to process the request. Since Spring MVC is built on top of Servlet, this is also the initial flow of request in any Spring MVC based Java web application.
Remember, Web container e.g. Tomcat is responsible for creating Servlet and Filter instances and invoking their various life-cycle methods e.g. init(), service(), destroy(). In the case of HTTP request, HttpServlet handles that and depending upon the HTTP request method various doXXX() method is invoked by container e.g. doGet() to process GET request and doPost() to process POST request.
If you remember, to enable Spring MVC, we need to declare the DispatcherServlet from 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.
Though it is not mandatory, you can have other servlet mapped to other URL if you want to, but if you are using Spring MVC to develop web application or RESTful web service, it make sense to pass through all request via DispatcherServlet.
Here is the web.xml configuration for Spring MVC, you can see that DispatcherServlet is mapped to all request using URL pattern *
Spring MVC Dispatcher Servlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation /WEB-INF/config/web-application-config.xml
1
example
*
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 the 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 mapping of request URL to different controllers. It can also use specific request processing annotations e.g. @GetMapping or @PostMapping. Controller classes are also identified using @Controller and @RestController (in the case of RESTful Web Services) annotations. See REST with Spring course by Eugen to learn how to develop RESTful Web Service using Spring in depth.
For example, below class is a Controller which will process any request having URI “/appointments”. It also has @GetMapping, which means that method will be invoked when a GET request is received for this URL. The method annotated with @PostMapping will be invoked if the client sends a POST request to the “/appointments”URI.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
@Controller @RequestMapping("/appointments") public class AppointmentsController { @GetMapping public Map get() { return appointmentBook.getAppointmentsForToday(); } @PostMapping public String add(@Valid AppointmentForm appointment, BindingResult result) { if (result.hasErrors()) { return "appointments/new"; } appointmentBook.addAppointment(appointment); return "redirect:/appointments"; } } |
After processing the request, Controller returns a logical view name and model to DispatcherServlet and it consults view resolvers 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 HTTP response. On it’s way back it can pass to any configured Filter as well e.g. 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 (see Patterns of Enterprise Application Architecture) 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.
It delegates requests for further processing to additional components e.g. Controllers, Views, View Resolvers, handler mappers, exception handlers etc. It can also map directly to /, but then the exception for handling static resources needs to be configured. If you look at the web.xml configuration it also pre-loaded using the load-on-startup tag.
- Spring MVC work Flow
It’s been often said that a picture is worth a thousand words and this is very true in the case of understanding system architecture and workflow of your application. Whatever I have said in above article, can be easily inferred by looking at following diagram which explains workflow of Spring MVC framework:
The flow of 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 HTTP response body. See Spring REST book to learn more about how to develop RESTful Web Services using Spring.
In summary, here is the flow of an HTTP request in Java application created using Spring MVC framework:
1) Client sends an HTTP request to a specific URL
2) DispatcherServlet of Spring MVC receives the request
2) It passes the request to a specific controller depending on the URL requested using @Controller and @RequestMapping annotations.
3) Spring MVC Controller then returns a logical view name and model to DispatcherServlet.
4) DispatcherServlet consults view resolvers until actual View is determined to render the output
5) DispatcherServlet contacts the chosen view (e.g. Thymeleaf, Freemarker, JSP) with model data and it renders the output depending on the model data
6) The rendered output is returned to the client as response
That’s all about what is the flow of Spring MVC or how an HTTP request is processed by Spring MVC. This is very basic but important knowledge about Spring MVC framework and every Java and Spring developer should be familiar with this. If you know how your HTTP request is processed then you can not only understand the issues better but also troubleshoot then easily and quickly.