我需要记录请求正文内容。因此,我为此目的使用了如下的过滤器和HttpServletRequestWrapper 。request.getParameter
但是当我从我的 servlet调用时,我什么也没得到。感谢任何帮助
请求包装代码
public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
private static final Log log = LogFactory.getLog(MultiReadHttpServletRequest.class);
private ByteArrayOutputStream cachedBytes;
public MultiReadHttpServletRequest(HttpServletRequest request) throws IOException {
super(request);
cachedBytes = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 4];
int n;
while (-1 != (n = request.getInputStream().read(buffer))) {
cachedBytes.write(buffer, 0, n);
}
}
@Override
public ServletInputStream getInputStream() throws IOException {
return new CachedServletInputStream();
}
private class CachedServletInputStream extends ServletInputStream {
private ByteArrayInputStream input;
public CachedServletInputStream() {
input = new ByteArrayInputStream(cachedBytes.toByteArray());
}
@Override
public int read() throws IOException {
return input.read();
}
}
String getRequestBody() throws IOException {
StringBuilder inputBuffer = new StringBuilder();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(getInputStream()));
try {
do {
line = reader.readLine();
if (null != line) {
inputBuffer.append(line.trim());
}
} while (line != null);
} catch (IOException ex) {
log.error("Unable to get request body from request: " + ex.getMessage(), ex);
} finally {
try {
reader.close();
} catch (IOException e) {
// Just log error
log.warn("Unable to close BufferReader: " + e.getMessage(), e);
}
}
return inputBuffer.toString().trim();
}
我的过滤代码
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
if ((servletRequest instanceof HttpServletRequest) && (messageTracerApiClient != null)) {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
MultiReadHttpServletRequest bufferedRequest = new MultiReadHttpServletRequest(httpServletRequest);
Message message = new Message();
message.setHost(bufferedRequest.getLocalAddr());
message.setPayload(bufferedRequest.getRequestBody());
messageTracerApiClient.publishMessage(message);
System.out.println("bufferedRequest param= " + bufferedRequest.getParameterMap().size());
filterChain.doFilter(bufferedRequest, servletResponse);
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
请注意bufferedRequest.getParameterMap().size()
,即使有参数,也要打印 0。