如何使用servlet过滤器保留请求体和响应体来记录请求和响应?

时间:2016-10-12 13:55:14

标签: java-ee java-ee-6 servlet-filters

我正在尝试在我的应用程序中记录每个传入请求和传出响应。我使用的是jee 6,所以我没有ContainerRequestFilter和ContainerResponseFilter类。所以我决定使用Filter。

我使用@WebFilter(“/ *”)注释了一个类并实现了Filter接口。我成功读取了请求标头和请求正文。有一些困难我也阅读了响应标题和响应正文。以下是代码段

MyHttpServletResponseWrapper wrapper = new MyHttpServletResponseWrapper((HttpServletResponse) response);
chain.doFilter(request, wrapper);

MyHttpServletResponseWrapper类

public class MyHttpServletResponseWrapper extends HttpServletResponseWrapper {
    private StringWriter sw = new StringWriter();
    public MyHttpServletResponseWrapper(HttpServletResponse response) { super(response); }

    public PrintWriter getWriter() { return new PrintWriter(sw); }

    public ServletOutputStream getOutputStream() {
        return new ServletOutputStream (){
            public void write(int B) { sw.append((char) B); }
        };
    }

    public String getCopy() { sw.toString(); }
}

记录响应后,我将响应写回输出流,以便客户端可以接收响应。以下是代码

logResponse(wrapper);
response.getOutputStream().write(wrapper.getCopy().getBytes());

我无法理解的是,如何在读取后将请求体放回输入流中。

在像Jersey这样的标准API中,有一种方便的方法可以使用setEntityInputStream(inputStream)将其放回去

如何使用标准Java ServletOutputStream api执行此操作。

我不想重新发明轮子。我试图避免使用Jersey,以便我的代码可以轻松迁移到新的jee版本。另外,我想了解像泽西岛这样的API是如何做到的。

要阅读身体的回复,我会阅读以下链接,但它对我不起作用。容器抛出一个例外,说作家已经获得了。

Capture and log the response body

P.S。

我想我想出了如何设置输入流。下面是一些代码

MyRequestWrapper requestwrapper = new MyRequestWrapper((HttpServletRequest) request);

chain.doFilter(requestwrapper,wrapper);

MyRequestWrapper类

public class MyRequestWrapper extends HttpServletRequestWrapper {
    String body; 
    int counter;
    public MyRequestWrapper(HttpServletRequest request) { super(request); }

    public void setBody(String body) { this.body = body;}

    public ServletInputStream getInputStream() {
        return new ServletInputStream() {
            public interest read() throws IOException {
                if(counter >=body.length()) return -1;
                return body.charAt(counter++);
            }
        };
    }
}

我知道覆盖getInputStream和getOutputStream的代码质量不是很好。现在我并不担心。我想知道这是不是一个正确的想法?如果那时我想专注于代码质量。

1 个答案:

答案 0 :(得分:1)

/** I know its too late but it can be helpfull for others as well. **//
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

public class ApiIOLoggerFilter implements Filter {
@Override 
public void init(FilterConfig filterConfig) {}
@Override 
public void destroy() {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) request);
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper((HttpServletResponse) response);
        try {
            chain.doFilter(requestWrapper, responseWrapper);
        } finally {
            performRequestAudit(requestWrapper);
            performResponseAudit(responseWrapper);
        }
    } else {
        chain.doFilter(request, response);
    }
}

private void performRequestAudit(ContentCachingRequestWrapper requestWrapper) {
    if (requestWrapper != null && requestWrapper.getContentAsByteArray() != null && requestWrapper.getContentAsByteArray().length > 0) {
        logger.info("\n Headers:: {} \n Request Body:: {}", new ServletServerHttpRequest((HttpServletRequest)requestWrapper.getRequest()).getHeaders(),
                getPayLoadFromByteArray(requestWrapper.getContentAsByteArray(), requestWrapper.getCharacterEncoding()));
    }
}

private void performResponseAudit(ContentCachingResponseWrapper responseWrapper)
        throws IOException {
    if (responseWrapper != null && responseWrapper.getContentAsByteArray() != null
            && responseWrapper.getContentAsByteArray().length > 0) {
        logger.info("Reponse Body:: {}", getPayLoadFromByteArray(responseWrapper.getContentAsByteArray(),
                responseWrapper.getCharacterEncoding()));
    } else {
        performErrorResponseAudit(responseWrapper);
    }
    responseWrapper.copyBodyToResponse();
}

private void performErrorResponseAudit(ContentCachingResponseWrapper responseWrapper) {
    logger.warn("HTTP Error Satus Code::" + responseWrapper.getStatus());
}

private String getPayLoadFromByteArray(byte[] requestBuffer, String charEncoding) {
    String payLoad = "";
    try {
        payLoad = new String(requestBuffer, charEncoding);
    } catch (UnsupportedEncodingException unex) {
        payLoad = "Unsupported-Encoding";
    }
    return payLoad;
}

}