我在我的java webserver(实际上是appengine)中创建了一个过滤器,用于记录传入请求的参数。我还想记录我的网络服务器写的结果响应。虽然我可以访问响应对象,但我不确定如何从中获取实际的字符串/内容响应。
有什么想法吗?
答案 0 :(得分:91)
您需要创建一个Filter
,其中您使用自定义HttpServletResponseWrapper
实施包装ServletResponse
参数,其中您覆盖getOutputStream()
和getWriter()
以返回自定义ServletOutputStream
实现,其中您复制基本抽象OutputStream#write(int b)
方法中的写入字节。然后,您将包装的自定义HttpServletResponseWrapper
传递给FilterChain#doFilter()
调用,最后您应该能够在调用之后获得复制的响应。
换句话说,Filter
:
@WebFilter("/*")
public class ResponseLogger implements Filter {
@Override
public void init(FilterConfig config) throws ServletException {
// NOOP.
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
if (response.getCharacterEncoding() == null) {
response.setCharacterEncoding("UTF-8"); // Or whatever default. UTF-8 is good for World Domination.
}
HttpServletResponseCopier responseCopier = new HttpServletResponseCopier((HttpServletResponse) response);
try {
chain.doFilter(request, responseCopier);
responseCopier.flushBuffer();
} finally {
byte[] copy = responseCopier.getCopy();
System.out.println(new String(copy, response.getCharacterEncoding())); // Do your logging job here. This is just a basic example.
}
}
@Override
public void destroy() {
// NOOP.
}
}
自定义HttpServletResponseWrapper
:
public class HttpServletResponseCopier extends HttpServletResponseWrapper {
private ServletOutputStream outputStream;
private PrintWriter writer;
private ServletOutputStreamCopier copier;
public HttpServletResponseCopier(HttpServletResponse response) throws IOException {
super(response);
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (writer != null) {
throw new IllegalStateException("getWriter() has already been called on this response.");
}
if (outputStream == null) {
outputStream = getResponse().getOutputStream();
copier = new ServletOutputStreamCopier(outputStream);
}
return copier;
}
@Override
public PrintWriter getWriter() throws IOException {
if (outputStream != null) {
throw new IllegalStateException("getOutputStream() has already been called on this response.");
}
if (writer == null) {
copier = new ServletOutputStreamCopier(getResponse().getOutputStream());
writer = new PrintWriter(new OutputStreamWriter(copier, getResponse().getCharacterEncoding()), true);
}
return writer;
}
@Override
public void flushBuffer() throws IOException {
if (writer != null) {
writer.flush();
} else if (outputStream != null) {
copier.flush();
}
}
public byte[] getCopy() {
if (copier != null) {
return copier.getCopy();
} else {
return new byte[0];
}
}
}
自定义ServletOutputStream
:
public class ServletOutputStreamCopier extends ServletOutputStream {
private OutputStream outputStream;
private ByteArrayOutputStream copy;
public ServletOutputStreamCopier(OutputStream outputStream) {
this.outputStream = outputStream;
this.copy = new ByteArrayOutputStream(1024);
}
@Override
public void write(int b) throws IOException {
outputStream.write(b);
copy.write(b);
}
public byte[] getCopy() {
return copy.toByteArray();
}
}
答案 1 :(得分:9)
BalusC解决方案没问题,但很少过时。 Spring现在有它的特色。您需要做的只是使用[ContentCachingResponseWrapper]
,其方法为public byte[] getContentAsByteArray()
。
我建议制作WrapperFactory,使其可以配置,无论是使用默认的ResponseWrapper还是ContentCachingResponseWrapper。
答案 2 :(得分:4)
虽然BalusC's answer在大多数情况下都可以使用,但您必须小心flush
调用 - 它会提交响应,而不能写其他任何内容,例如。通过以下过滤器。
我们在Websphere环境中发现了一些非常类似的问题,其中交付的响应只是部分的。
根据this question,根本不应该调用flush,你应该让它在内部调用。
我通过使用TeeWriter
(它将流分成2个流)并在"分支流"中使用非缓冲流解决了刷新问题。用于记录目的。那么在flush
打电话是不必要的。
private HttpServletResponse wrapResponseForLogging(HttpServletResponse response, final Writer branchedWriter) {
return new HttpServletResponseWrapper(response) {
PrintWriter writer;
@Override
public synchronized PrintWriter getWriter() throws IOException {
if (writer == null) {
writer = new PrintWriter(new TeeWriter(super.getWriter(), branchedWriter));
}
return writer;
}
};
}
然后你可以这样使用它:
protected void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException {
//...
StringBuilderWriter branchedWriter = new org.apache.commons.io.output.StringBuilderWriter();
try {
chain.doFilter(request, wrapResponseForLogging(response, branchedWriter));
} finally {
log.trace("Response: " + branchedWriter);
}
}
为了酿造而简化了代码。
答案 3 :(得分:3)
我对appengine不是很熟悉,但你在Tomcat中需要一些Access Log Valve。其属性模式;格式化布局,用于标识请求和要记录的响应中的各种信息字段,或单词common或combined以选择标准格式。
看起来appengine内置了log filtering的功能。
答案 4 :(得分:0)
与其创建自定义HttpServletResponseWrapper,还可以使用ContentCachingResponseWrapper,因为它提供了getContentAsByteArray()方法。
public void doFilterInternal(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = servletRequest;
HttpServletResponse response = servletResponse;
ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
ContentCachingResponseWrapper responseWrapper =new ContentCachingResponseWrapper(response);
try {
super.doFilterInternal(requestWrapper, responseWrapper, filterChain);
} finally {
byte[] responseArray=responseWrapper.getContentAsByteArray();
String responseStr=new String(responseArray,responseWrapper.getCharacterEncoding());
System.out.println("string"+responseStr);
/*It is important to copy cached reponse body back to response stream
to see response */
responseWrapper.copyBodyToResponse();
}
}