为何一次请求会有两次HttpServlet:service调用?
为什么只访问了
http://localhost:8080/a.txt
,但Arthas的trace
命令打印出了两个请求树?
然后我去自己试了下,发现还真的是这个情况,trace日志如下:
1 | `---ts=2019-02-24 18:05:20;thread_name=http-nio-8080-exec-1;id=15;is_daemon=true;priority=5;TCCL=org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedWebappClassLoader@6601a0f8 |
然后,过去翻了一下代码才发现,是org.apache.catalina.core.StandardHostValve#invoke
方法的逻辑:
1 | //正常的处理请求(这是第一个HttpServlet:service调用) |
在status方法中,获取ErrorPage
,然后给request
设置javax.servlet.error.*
的属性,然后再forward到HttpServlet:service
。这儿就会出现第二个HttpServlet:service
请求。
那么问题来了,这个行为是规范里面有约定吗?
翻了翻 Java Servlet Specification,第10.9.2小节有说:
To allow developers to customize the appearance of content returned to a Web client when a servlet generates an error, the deployment descriptor defines a list of error page descriptions. The syntax allows the configuration of resources to be returned by the container either when a servlet or filter calls sendError on the response for specific status codes, or if the servlet generates an exception or error that propagates to the container.
If the sendError method is called on the response, the container consults the list of error page declarations for the Web application that use the status-code syntax and attempts a match. If there is a match, the container returns the resource as indicated by the location entry.
The Web application may have declared error pages using the exception-typeelement. In this case the container matches the exception type by comparing the exception thrown with the list of error-page definitions that use the exception-typeelement. A match results in the container returning the resource indicated in the location entry. The closest match in the class hierarchy wins.
简而言之,如果通过sendError方法设置了错误,就会被对应的ErrorPage对象处理,就会转发到对应的location去处理。
其实到这儿,还有很多问题没有解决,比如:
- ErrorPage是如何设置的?
- war模式下,容器是如何知晓spring的入口的?
不过,慢慢来吧。
最近在写Java的时候,同时使用VSCode和IntelliJ IDEA,发现IDEA在很多细节做了优化,比如debug的时候,IDEA是选中了某一个线程,展示某一个线程的调用栈;而VSCode则是用一个Tree来表示,第一级是线程,更深的则是调用栈。还有,IDEA在展示Map等数据结构的时候,直接展示key、value对,而VSCode则暴露了很多内部实现,很不直观。VSCode还有很多路要走啊……
为何一次请求会有两次HttpServlet:service调用?
https://robberphex.com/why-is-there-two-httpservlet-service-call/