java servlet filter 记录请求与响应日志

问题所在

在filter的doFilter(ServletRequest request, ServletResponse response, FilterChain chain)方法中我们可以取到request和response两个对象,形参中是接口,实际实现和web容器相关。在获取request中请求内容以及reponse中的响应内容时候,遇到如下两个问题:

  1. request.getInputStream()的设计实现只能读一次(未实现reset方法),如果记录日志时候读取过,后续不能读取
  2. response.getOutputStream()的具体实现依赖web容器,而且ServletOutputStream作为抽象类是被web容器继承来使用的,无法获取outputstream中的内容。

方案

为了解决上述问题,采取如下方案

针对问题1

针对request的inputstream不能重复读问题,继承HttpServletRequestWrapper,实现request请求内容的缓存。代码参考如下

public class LoggingHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private ByteArrayOutputStream cachedBytes;

    public LoggingHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (cachedBytes == null) {
            cacheInputStream(); //1. 将请求内容缓存到cachedBytes
        }

        return new CachedServletInputStream();//2. 当需要获取ServletInputStream时候,返回自定义实现的内部类
    }

    @Override
    public BufferedReader getReader() throws IOException{
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    private void cacheInputStream() throws IOException {
    /* Cache the inputstream in order to read it multiple times. For
     * convenience, I use apache.commons IOUtils
     */
        cachedBytes = new ByteArrayOutputStream();
        IOUtils.copy(super.getInputStream(), cachedBytes);
    }

    /* An inputstream which reads the cached request body */
    public class CachedServletInputStream extends ServletInputStream {
        private ByteArrayInputStream input;

        public CachedServletInputStream() {
      /* create a new input stream from the cached request body */
            input = new ByteArrayInputStream(cachedBytes.toByteArray());3. 使用缓存的请求内容初始化ByteArrayInputStream 
        }

        @Override
        public boolean isFinished() {
            return false;
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setReadListener(ReadListener readListener) {

        }

        @Override
        public int read() throws IOException {
            return input.read(); //4. 当外部调用ServletInputStream的read方法时候,使用初始化的input来返回
        }
    }

LoggingHttpServletRequestWrapper 自定义实现说明如下

  1. 将请求内容写到ByteArrayOutputStream cachedBytes来缓存
  2. 当需要获取ServletInputStream时候,返回自定义实现的内部类CachedServletInputStream
  3. CachedServletInputStream 使用缓存的cachedBytes内容初始化其私有字段ByteArrayInputStream input
  4. 当外部调用ServletInputStream的read方法时候,使用初始化的input来返回

如上所述就能实现request请求内容的多次读,使用代码如下

 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)  {
    LoggingHttpServletRequestWrapper multiReadRequest = new LoggingHttpServletRequestWrapper((HttpServletRequest) request);
   chain.doFilter(multiReadRequest,response);
}

针对问题2

同样,针对不能获取ServletOutputStream内容的问题,需要继承HttpServletResponseWrapper,代码参考如下

public class LoggingHttpServletResponseWrapper extends HttpServletResponseWrapper {
    private final LoggingServletOutpuStream loggingServletOutpuStream = new LoggingServletOutpuStream(); //1. 也是实现了自定义的ServletOutputStream内部类LoggingServletOutpuStream,并初始化

    private final HttpServletResponse delegate;

    public LoggingHttpServletResponseWrapper(HttpServletResponse response) {
        super(response);
        delegate = response;
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return loggingServletOutpuStream; 2. 当外部获取ServletOutputStream时候返回内部实现类
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        return new PrintWriter(loggingServletOutpuStream.baos);
    }

    public Map getHeaders() {
        Map headers = new HashMap<>(0);
        for (String headerName : getHeaderNames()) {
            headers.put(headerName, getHeader(headerName));
        }
        return headers;
    }

    public String getContent() {
        try {
            String responseEncoding = delegate.getCharacterEncoding();
            return loggingServletOutpuStream.baos.toString(responseEncoding != null ? responseEncoding : UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            return "[UNSUPPORTED ENCODING]";
        }
    }

    public byte[] getContentAsBytes() {
        return loggingServletOutpuStream.baos.toByteArray(); 4. 获取请求内容时候从内部实现类的私有变量返回
    }

    private class LoggingServletOutpuStream extends ServletOutputStream {

        private ByteArrayOutputStream baos = new ByteArrayOutputStream();

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {
        }

        @Override
        public void write(int b) throws IOException {
            baos.write(b);
        }

        @Override
        public void write(byte[] b) throws IOException {
            baos.write(b);
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            baos.write(b, off, len);  3. 当向内部实现类LoggingServletOutpuStream 写入信息时,写到其内部字段baos上
        }
    }

LoggingHttpServletResponseWrapper 自定义实现说明如下

  1. 也是实现了自定义的ServletOutputStream内部类LoggingServletOutpuStream,并初始化
  2. 当外部获取ServletOutputStream时候返回内部实现类
  3. 当向内部实现类LoggingServletOutpuStream 写入信息时,写到其内部字段baos上
  4. 获取请求内容时候从内部实现类的私有变量返回

如上所述就能实现获取response的内容,使用代码如下

 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)  {
      LoggingHttpServletRequestWrapper multiReadRequest = new LoggingHttpServletRequestWrapper((HttpServletRequest) request);
      LoggingHttpServletResponseWrapper responseWrapper = new LoggingHttpServletResponseWrapper((HttpServletResponse) response);
      chain.doFilter(multiReadRequest,contentWrapper );
      response.getOutputStream().write(contentWrapper.getContentAsByteArray());//最后注意需要请reponsewrapper的内容写入到原始response
      String s = contentWrapper.getContent();//就能获取到内容
}

其实对于ResponseWrapper有现成的实现,就是ContentCachingResponseWrapper,因此上述代码可以变更如下

 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)  {
      ContentCachingResponseWrappermultiReadRequest = new ContentCachingResponseWrapper((HttpServletRequest) request);
      LoggingHttpServletResponseWrapper responseWrapper = new LoggingHttpServletResponseWrapper((HttpServletResponse) response);
      chain.doFilter(multiReadRequest,contentWrapper );
    byte[] s = contentWrapper .getContentAsByteArray();//就能获取到内容
      contentWrapper.copyBodyToResponse();//最后注意需要请reponsewrapper的内容写入到原始response, 最后一步执行,因为执行完后ContentCachingResponseWrapper的FastByteArrayOutputStream会被重置  
}

拿到请求内容和响应内容后,就可以自由记录日志了,在此不在赘述。

你可能感兴趣的:(java servlet filter 记录请求与响应日志)