拦截请求(request)和响应(response)信息

思路

  1. 使用拦截器;
  2. 使用Filter;

实现

  1. 使用拦截器时不能获取到返回的信息(response里的content为空);
  2. 使用Filter,成功获取到内容:
@WebFilter(urlPatterns = "/*")
public class GlobalFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(GlobalFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 拦截请求和相应信息,并保存到数据库中
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        WkResponseWrapper wrapper = new WkResponseWrapper((HttpServletResponse)response);
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) request);
        HttpServletRequest req = (HttpServletRequest) request;
        String params = "";

        try {

            chain.doFilter(requestWrapper, wrapper);
            String responseContent = new String(wrapper.getDataStream());

            String method = req.getMethod();
            if ("POST".equalsIgnoreCase(method)) {
                params = new String(requestWrapper.getContentAsByteArray());
            } else if ("GET".equalsIgnoreCase(method)) {
                params = JSON.toJSONString(request.getParameterMap());
            }

            response.getWriter().write(responseContent);


        } catch (Exception e) {
            logger.error("保存请求和相应信息时出现异常:", e);
        }
    }

    @Override
    public void destroy() {

    }


}

public class WkResponseWrapper  extends HttpServletResponseWrapper {
    ByteArrayOutputStream output;
    FilterServletOutputStream filterOutput;

    public WkResponseWrapper(HttpServletResponse response) {
        super(response);
        output = new ByteArrayOutputStream();
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        if (filterOutput == null) {
            filterOutput = new FilterServletOutputStream(output);
        }
        return filterOutput;
    }

    public byte[] getDataStream() {
        return output.toByteArray();
    }


    class FilterServletOutputStream extends ServletOutputStream {
        DataOutputStream output;

        public FilterServletOutputStream(OutputStream output) {
            this.output = new DataOutputStream(output);
        }

        @Override
        public void write(int arg0) throws IOException {
            output.write(arg0);
        }

        @Override
        public void write(byte[] arg0, int arg1, int arg2) throws IOException {
            output.write(arg0, arg1, arg2);
        }

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

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

        @Override
        public void setWriteListener(WriteListener writeListener) {

        }
    }
}

你可能感兴趣的:(java,SpringBoot)