Thursday, April 18, 2024

How Spring MVC Framework works? How HTTP Request is processed?

Hello guys, one of the frequently asked Spring MVC Interview questions is about explaining the flow of web requests i.e. how an HTTP request is processed from start to end. In other words, explaining the flow of requests 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 hits the web container like Tomcat it looks into web.xml and finds 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 requests in any Spring MVC based Java web application.

Remember, Web container like Tomcat is responsible for creating Servlet and Filter instances and invoking their various life-cycle methods like init(), service(), destroy(). In the case of an HTTP request, HttpServlet handles that, and depending upon the HTTP request method various doXXX() method is invoked by container like 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 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.

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 a web application or RESTful web service, it makes sense to pass through all requests via DispatcherServlet.

By the way, if you are new to the Spring framework then I also suggest you join a comprehensive and up-to-date course to learn Spring in depth. If you need recommendations, I highly suggest you take a look at Spring Framework 6: Beginner to Guru, one of the comprehensive and hands-on courses to learn modern Spring. It' also the most up-to-date and covers Spring 6.


How Spring MVC process an HTTP Request?

Here is the web.xml configuration for Spring MVC, you can see that Dispatcher Servlet is mapped to all request using URL pattern *

<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. See REST with Spring course by Eugen to learn how to develop RESTful Web Service using Spring in depth.

how does spring mvc work?



For example, the below class is a Controller that will process any request having URI "/appointments"

It also has @GetMapping, which means that the 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.

@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, the 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 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 (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 like 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 the system architecture and workflow of your application. 

Whatever I have said in the above article, can be easily inferred by looking at the following diagram which explains the workflow of the Spring MVC framework as explained in the Spring Framework: Spring MVC Fundamentals course by Bryan Hansen on Pluralsight. 

How Spring MVC Framework works

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.


You can further see Spring REST book to learn more about how to develop RESTful Web Services using Spring.

How Spring MVC Framework works? How HTTP Request is processed?


In summary, here is the flow of an HTTP request in Java application created using the Spring MVC framework:

1) The 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 (like 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 a 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 the 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 them easily and quickly.


Other Java and Spring Articles you may like
  • 15 Spring Boot Interview Questions for Java Developers (questions)
  • Top 5 Courses to Learn and Master Spring Cloud (courses)
  • 21 Spring MVC and REST Interview questions (answers)
  • 5 Free Courses to Learn Spring Framework for beginners (free courses)
  • 5 Courses to Learn Spring Security for beginners (courses)
  • 17 Spring AOP Interview Questions with answers (questions)
  • Top 5 Spring Boot Annotations Java Developers should know (read)
  • 5 Courses to learn Spring Cloud for beginners (courses)
  • 10 Advanced Spring Boot Courses for Java developers (courses)
  • Top 7 Courses to learn Microservices in Java (courses)
  • Top 5 Spring Cloud annotations Java programmer should learn (cloud)
  • 10 Free Courses to learn Spring Framework for Beginners (free courses)
  • 20 Spring Boot Interview Questions for Java developers (questions)
  • @SpringBootApplication vs @EnableAutoConfiguration? (answer)
  • 5 Spring Books Experienced Java Developer Should Read  (books)
  • Top 5 Frameworks Java Developer Should Know (frameworks)
  • 7 Best Spring Courses for Beginners and Experienced (courses)
  • 10 Spring MVC annotations Java developer should learn (annotations)
  • 10 Free Courses to learn Spring Boot in-depth (free courses)

Thanks a lot for reading this article so far. If you like this Spring MVC tutorial then please share it with your friends and colleagues. If you have any questions or suggestions then please drop a note and I'll try to answer your question.

P.S. - If you want to learn how to develop RESTful Web Service using Spring MVC in-depth, I suggest you join the REST with Spring certification class by Eugen Paraschiv. One of the best courses to learn REST with Spring MVC. 

13 comments:

  1. Very nice explanation

    ReplyDelete
  2. Thanks you @Anonymous, happy that you find my explanation of how Spring MVC works and process requests useful.

    ReplyDelete
  3. good one but u should explain flow with restful web services

    ReplyDelete
  4. Hello Anonymous, sure, will write another blog post to explain spring mvc flow with restful web service, but most part are same, except that RESTful web service directly write to response instead of returning view name. They use @ResponseBody annotation on handler method, which allows them to write directly to HTTP response.

    ReplyDelete
  5. Looking forward to explain flow with restful web services

    ReplyDelete
  6. I suppose you have mentioned wrong name of servlet in servlet mapping while you declare dispatcher servlet in web. xml.

    ReplyDelete
    Replies
    1. I think name should be example.

      Delete
  7. Very well explained !

    ReplyDelete
  8. Suppose @requestMapping("data") on class and has 10 different path method, then internally how many server createf?

    ReplyDelete
  9. Thank you for explaining :) I have a question; after reading I am a little confused. How does Spring identify the index page or the default page?

    ReplyDelete
  10. Hello Daneil. Spring internally use Servlet technology, so what is definite as index.jsp or index.html in web.xml or accordingly in Java configuration is used.

    ReplyDelete