Many Java interviewers like to ask this question:

In a Spring MVC project file, instead of developing their own servlets, the @requestMapping annotation defines the method home to respond to requests sent to/MVC /test1.

Use the url http://localhost:9098/MavenSandbox/mvc/test1 test, the home can be observed () method returns the string, what is the principle behind this?

We answer with our own research. Set a breakpoint at line 53 above. Visit the url http://localhost:9098/MavenSandbox/mvc/test1 again, triggered a breakpoint. We observed the call stack, discovered that a stack frame DispatcherServlet. DoService (it, HttpServletResponse). This Servlet is responsible for adding the return string from our @requestMapping method to HttpServletResponse, which is why we see the return string in the browser.

We look at the DispatcherServlet. Whether in the HttpServletResponse doService contains we expect output string. Expand the response variable in the debugger:

Response ->outputBuffer->bb->buff

104 is the ASCII code of H, 101 is the ASCII code of E, and 108 is the ASCII code of L, so it proves that response does contain the string returned by the developer in the home method: Hello this is a most simple example

Finally, where did the DispatcherServlet come from?

Found in the Eclipse debugger, which is a standard Servlet for the Spring framework:

org.springframework.web.servlet.DispatcherServlet

This Servlet is the same Servlet in our web.xml file in the WEB-INF folder.

So the answer for the interviewer is: The Spring MVC framework still needs servlets, but the servlets are provided by the Spring framework and don’t need to be implemented repeatedly by application developers.

For more of Jerry’s original technical articles, please follow the public account “Wang Zixi” or scan the following QR code: