The content of this article is about why Spring MVC can respond to HTTP requests? (Detailed explanation of the reasons), it has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Many Java interviewers like to ask this question:
In a Spring MVC project file, the developer did not develop his own Servlet, but only defined the method home function through the annotation @RequestMapping Respond to requests to /mvc/test1.
Use the url http://localhost:9098/MavenSandbox/mvc/test1 to test and you can observe the string returned by the home method. Behind this How does it work?
We answer through our own research. Set a breakpoint on line 53 of the above code. Visit the url http://localhost:9098/MavenSandbox/mvc/test1 again, and the breakpoint is triggered. We observe the call stack and find that there is a stack frame DispatcherServlet.doService(HttpServletRequest, HttpServletResponse). This Servlet will be responsible for adding the return string in the method annotated with @RequestMapping to the HttpServletResponse. This is why we can see the return string in the browser.
Let’s see if the HttpServletResponse in DispatcherServlet.doService contains the output string we expect. Expand the response variable in the debugger:
##response->outputBuffer->bb->buff, you can see this in buff String array buffer:
104 is the ASCII code of H, 101 is the ASCII code of e, and 108 is the ASCII code of l, so it is proved The response does contain the string returned by the developer in the home method: hello this is a most simple example Finally, where does the DispatcherServlet come from? Found in the Eclipse debugger, it is a standard Servlet of the Spring framework: org.springframework.web.servlet.DispatcherServlet
This Servlet is exactly the Servlet in our web.xml file in the WEB-INF folder. So the answer to the interviewer is: The Spring MVC framework still requires Servlet, but this Servlet is provided by the Spring framework and does not need to be implemented repeatedly by application developers.
The above is the detailed content of Why can Spring MVC respond to HTTP requests? (Detailed explanation of reasons). For more information, please follow other related articles on the PHP Chinese website!