How to access HTTP response body in Tomcat error page
I am using Tomcat 6 (but the same applies to Tomcat 7). Let's say my web.xml
contains this definition:
<error-page>
<error-code>401</error-code>
<location>/Handle401Error.jsp</location>
</error-page>
Suppose I am now returning HTTP 401 from another servlet / JSP:
httpResponse.sendError(SC_UNAUTHORIZED, "This is a message");
How do I access the HTTP response text ("This message") in Handle401Error.jsp
? This is how Tomcat does it when it shows an error page like this
used with Valve
( ErrorReportValve
). Do I also need to write Valve
?
Edit: The accepted answer below is exactly what I was looking for and the supposed duplicate of this question does not mention the same solution.
source to share
Tomcat stores the message string in an inner class org.apache.coyote.Response
.
There is no standard way to access the message: from the javadoc HttpServletResponse # sendError (int, String):
If an error page declaration has been made for a web application matching the passed status code, it will be returned in preference to the suggested msg parameter and the msg parameter will be ignored .
Poor API design.
As a workaround, you can put the error message as an attribute in the request, just call response.sendError (401), and on the error page, extract the message from the request attributes:
In your code:
HttpServletRequest request = ...
HttpServletResponse response = ...
request.setAttribute("myerrormessage", "This is a message");
response.sendError(401);
In your jsp error page:
Message <%=request.getAttribute("myerrormessage")%>
source to share