我使用的是 Tomcat 6(但同样适用于 Tomcat 7)。假设我的 web.xml
包含以下定义:
<error-page>
<error-code>401</error-code>
<location>/Handle401Error.jsp</location>
</error-page>
假设我现在从其他一些 servlet/JSP 返回 HTTP 401:
httpResponse.sendError(SC_UNAUTHORIZED, "This is a message");
如何访问 Handle401Error.jsp
中的 HTTP 响应文本(“这是一条消息”)? Tomcat 这样做的方式,当它显示这样的错误页面时
是通过使用Valve
(ErrorReportValve
)。我还需要编写一个 Valve
吗?
编辑:下面接受的答案正是我一直在寻找的,这个问题的假定重复没有提到相同的解决方案。
最佳答案
Tomcat 将消息字符串存储在内部类 org.apache.coyote.Response
中。
没有访问消息的标准方法:来自 HttpServletResponse#sendError(int,String) 的 javadoc:
If an error-page declaration has been made for the web application corresponding to the status code passed in, it will be served back in preference to the suggested msg parameter and the msg parameter will be ignored.
糟糕的 API 设计。
作为解决方法,您可以将错误消息作为属性放入请求中,只需调用 response.sendError(401) 并在错误页面中从请求属性中提取消息:
在您的代码中:
HttpServletRequest request = ...
HttpServletResponse response = ...
request.setAttribute("myerrormessage", "This is a message");
response.sendError(401);
在你的错误jsp页面中:
Message <%=request.getAttribute("myerrormessage")%>
关于java - 如何访问 Tomcat 错误页面中的 HTTP 响应文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31314282/