I have the following in my web.xml:
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error/exception</location>
</error-pa开发者_JAVA技巧ge>
The path /error/exception
is a servlet.
My question is: is there a way to forward the request that caused the exception to the error-page defined in the web.xml?
The above creates a new request
This is not true. Unless you're sending a redirect inside the servlet of course, but that would be a too obvious mistake.
I want the request body of the request that caused the exception.
The request body can be read only once. The client ain't going to resend it once again whenever you want to read it once again. In case of normal application/x-www-form-urlencoded
POST requests, the server will read and parse the request body into request parameters as you get by HttpServletRequest#getParameterMap()
. If you don't want to display all request parameters in a nice list/table for some unobvious reason, then you can also just reconstruct the request body based on the request parameter map. E.g.
String requestBody = toQueryString(request.getParameterMap());
// ...
with
public static String toQueryString(Map<String, String[]> params) {
StringBuilder queryString = new StringBuilder();
for (Entry<String, String[]> param : params.entrySet()) {
for (String value : param.getValue()) {
if (queryString.length() > 0) {
queryString.append("&");
}
queryString
.append(URLEncoder.encode(param.getKey(), "UTF-8"))
.append("=")
.append(URLEncoder.encode(value, "UTF-8"));
}
}
return queryString.toString();
}
In case of multipart/form-data
requests, well, that depends on how you're parsing the request body and storing the data. Reconstructing is also less trivial.
If you want a completely transparent solution, consider a HttpServletRequestWrapper
which copies the request body to a local (byte) buffer (or temp file when it exceeds a certain threshold) whenever getInputStream()
or getReader()
is called. Then, just cast the HttpServletRequest
to your wrapper implementation and grab that copy.
精彩评论