Spring MVC能响应HTTP请求的原因?
很多Java面试官喜欢问这个问题:
一个Spring MVC的项目文件里,开发人员没有开发自己的Servlet,只通过注解@RequestMapping定义了方法home能响应发向 /mvc/test1的请求。

使用url http://localhost:9098/MavenSandbox/mvc/test1 测试,能观察到home方法返回的字符串,这背后的工作原理是什么?

我们通过自己的研究来回答。在上述代码第53行设置断点。再次访问url http://localhost:9098/MavenSandbox/mvc/test1,断点触发。我们观察调用栈,发现有一个栈帧DispatcherServlet.doService(HttpServletRequest, HttpServletResponse)。这个Servlet会负责将我们加了@RequestMapping注解的方法里return的字符串加到HttpServletResponse里,这就是为什么我们在浏览器里能看到return字符串的原因。

我们看下DispatcherServlet.doService里的HttpServletResponse里是否包含了我们期望的输出字符串。在调试器里展开response变量:

response->outputBuffer->bb->buff, 在buff里能看到这个字符串数组缓冲:

104是H的ASCII码,101是e的ASCII码,108是l的ASCII码,所以证明了response确实包含了开发人员在home方法里返回的字符串:hello this is a most simple example
最后,DispatcherServlet从哪里来的?
在Eclipse调试器里发现,它是Spring框架的标准Servlet:
org.springframework.web.servlet.DispatcherServlet

这个Servlet正是我们在WEB-INF文件夹的web.xml文件里的Servlet。
因此给面试官的答案为:Spring MVC框架仍然需要Servlet,但这个Servlet是由Spring框架提供,无需应用开发人员重复实现。

要获取更多Jerry的原创技术文章,请关注公众号"汪子熙"或者扫描下面二维码:

