相关推荐recommended
SpringBoot自定义过滤器获取HttpServletRequest和HttpServletResponse的参数
作者:mmseoamin日期:2024-02-03

1、 需求:

公司的老系统改造:由于接口日志不全,接口太多,也无法每个接口都加上日志,所以要在网关层统一记录一下日志,并存到数据库中,(以后计划要存储到ES中)

2、了解过滤器:

过滤器是基于Servlet规范的组件,作用于整个请求和响应过程,无法直接访问Spring MVC的上下文。过滤器先于拦截器执行,过滤器的执行顺序由注册顺序决定,拦截器的执行顺序由配置的顺序决定。

实现方式:

  • 过滤器是基于Servlet规范的一部分,需要实现javax.servlet.Filter接口来创建自定义过滤器。javax.servlet.Filter接口定义了以下三个方法:
    • void init(FilterConfig config) throws ServletException:

      该方法在过滤器初始化时被调用,用于进行初始化操作。

      参数config包含了过滤器的配置信息,可以通过该对象获取配置参数。

    • void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException:

      该方法在每次请求被过滤时被调用,用于对请求和响应进行过滤和处理。

      参数request表示当前的请求对象,参数response表示当前的响应对象,参数chain表示过滤器链。

      在该方法中可以对请求和响应进行修改或包装,并通过调用chain.doFilter(request, response)方法将请求传递给下一个过滤器或目标资源。

    • void destroy():

      该方法在过滤器被销毁时被调用,用于进行清理操作。

      拦截器和过滤器的区别可以参考:

      https://blog.csdn.net/xiaoweiwei11/article/details/130860352

      3、开发难点

      3.1 HttpServletRequest 的Post请求方式,获取不到入参

      3.1.1 原因:

      获取json入参的时候,一般都是用流的方式获取,但是会引发另外一个问题:过滤器相关逻辑走完之后,接口层的@RequestBody修饰的对象参数都会失效,并且调试之后释放会报错

      org.springframework.http.converter.HttpMessageNotReadableException: I/O error while reading input message; nested exception is java.io.IOException: Stream closed
      

      因为用了流,并且存在流关闭,一次请求流关闭了就只能读取一次,所以到接口层就会报错

      3.1.2 解决思路:

      不管流关没关闭,要把流中的参数,延伸到后面的接口去用就可以了

      3.1.3 代码实现

      需要

      • 过滤器:HttpServletRequestFilter
      • 过滤器:AccessLogFilter 调用接口记录日志
      • 防流丢失类:MyRequestWrapper (防止流读取完之后就丢失了)
      • 过滤器Bean(在springboot的启动类中注入过滤器):FilterRegistrationBean
      • 获取参数的类:HttpRequestHelper
        /**
         * 获取参数的类
         * @description: 获取流并将想要的结果通过拼接返回
         **/
        public class HttpRequestHelper {
            public static String getBodyString(HttpServletRequest request) throws IOException {
                StringBuilder sb = new StringBuilder();
                InputStream inputStream = null;
                BufferedReader reader = null;
                try {
                    inputStream = request.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
                    String line = "";
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                return sb.toString();
            }
        }
        
        /**
         * @description: 防止流丢失
         **/
        public class MyRequestWrapper extends HttpServletRequestWrapper {
            private final byte[] body;
         
            public MyRequestWrapper(HttpServletRequest request) throws IOException {
                super(request);
                //返回参数字节数组
                body = HttpRequestHelper.getBodyString(request).getBytes(Charset.forName("UTF-8"));
            }
         
            @Override
            public BufferedReader getReader() throws IOException {
                return new BufferedReader(new InputStreamReader(getInputStream()));
            }
         
            @Override
            public ServletInputStream getInputStream() throws IOException {
         
                final ByteArrayInputStream bais = new ByteArrayInputStream(body);
         
                return new ServletInputStream() {
         
                    @Override
                    public int read() throws IOException {
                        return bais.read();
                    }
         
                    @Override
                    public boolean isFinished() {
                        return false;
                    }
         
                    @Override
                    public boolean isReady() {
                        return false;
                    }
         
                    @Override
                    public void setReadListener(ReadListener readListener) {
         
                    }
                };
            }
         
        }
        
        /**
         * @description: 使用过滤器处理流,将当前流放到一个新的request对象中
         **/
        public class HttpServletRequestFilter implements Filter {
            @Override
            public void destroy() {
         
            }
         
            @Override
            public void doFilter(ServletRequest request, ServletResponse response,
                                 FilterChain chain) throws IOException, ServletException {
                ServletRequest requestWrapper = null;
                if (request instanceof HttpServletRequest) {
                    requestWrapper = new MyRequestWrapper((HttpServletRequest) request);
                }
                //获取请求中的流如何,将取出来的字符串,再次转换成流,然后把它放入到新request对象中。
                // 在chain.doFiler方法中传递新的request对象
                if (requestWrapper == null) {
                    chain.doFilter(request, response);
                } else {
                    chain.doFilter(requestWrapper, response);
                }
            }
         
            @Override
            public void init(FilterConfig arg0) throws ServletException {
         
            }
        }
        
        @Slf4j
        @Component
        public class AccessLogFilter extends OncePerRequestFilter {
            @Value("${spring.profiles.active}")
            private String springProfile;
            @Value("${log-application.ignore-uri}")
            private String ignoreURIs;
            @Reference(check = false)
            private WebOperateLogService webOperateLogService;
            @Override
            protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
                    throws ServletException, IOException {
                    // 重点:MyRequestWrapper 
                MyRequestWrapper req = new MyRequestWrapper(request);
                // 解决:获取不到HttpServletResponse响应信息
                ContentCachingResponseWrapper resp = new ContentCachingResponseWrapper(response);
                try {
                    // Execution request chain
                    filterChain.doFilter(req, resp);
                    //URI白名单
                    boolean haveIgnoreURI = Arrays.stream(ignoreURIs.split(",")).anyMatch(ignoreURI -> request.getRequestURI().contains(ignoreURI));
                    if (!haveIgnoreURI) {
                        saveWebRequestLog(request, response, resp);
                    }
                } catch (Exception e) {
                    log.error("记录WEB接口日志异常!原因:" + e);
                } finally {
                    // Finally remember to respond to the client with the cached data.
                    resp.copyBodyToResponse();
                }
            }
            private void saveWebRequestLog(HttpServletRequest request, HttpServletResponse response, ContentCachingResponseWrapper resp) throws Exception {
                WebOperateLog webOperateLog = new WebOperateLog();
                String method = request.getMethod();
                webOperateLog.setMethod(request.getMethod());
                webOperateLog.setRequestUrl(request.getRequestURI());
                String inputParams = StringSymbolEnum.EMPTY.getCode();
                if (method.equals("GET")) {
                    inputParams = request.getQueryString();
                } else {
                // 重点
                    inputParams = HttpRequestHelper.getBodyString(request);
                }
                webOperateLog.setInputParams(inputParams);
                webOperateLog.setServletPath(request.getServletPath());
                webOperateLog.setRemoteAddr(request.getRemoteAddr());
                webOperateLog.setRemoteHost(request.getRemoteHost());
                webOperateLog.setRemotePort(StringSymbolEnum.EMPTY.getCode() + request.getRemotePort());
                webOperateLog.setRemoteAddr(request.getLocalAddr());
                webOperateLog.setLocalAddr(request.getLocalName());
                webOperateLog.setLocalPort(StringSymbolEnum.EMPTY.getCode() + request.getLocalPort());
                webOperateLog.setServerName(request.getServerName());
                webOperateLog.setServerPort(StringSymbolEnum.EMPTY.getCode() + request.getServerPort());
                webOperateLog.setRequestUrl(request.getRequestURL().toString());
                String outputParams = StringSymbolEnum.EMPTY.getCode();
                if (!ObjectUtils.isEmpty(response)) {
                    webOperateLog.setStatus(StringSymbolEnum.EMPTY.getCode() + response.getStatus());
                    // 重点
                    byte[] responseBody = resp.getContentAsByteArray();
                    if (responseBody != null && responseBody.length > 0) {
                        outputParams = new String(responseBody, StandardCharsets.UTF_8);
                        webOperateLog.setOutputParams(outputParams);
                    }
                }
                webOperateLog.setCreatedDate(new Date());
                webOperateLog.setProfile(springProfile);
                webOperateLogService.save(webOperateLog);
            }
        }
        
            @Bean
            public FilterRegistrationBean httpServletRequestReplacedRegistration() {
                FilterRegistrationBean registration = new FilterRegistrationBean();
                registration.setFilter(new HttpServletRequestFilter());
                registration.addUrlPatterns("/*");
                registration.addInitParameter("paramName", "paramValue");
                registration.setName("httpServletRequestFilter");
                registration.setOrder(1);
                return registration;
            }
        

        3.2 HttpServletResponse: 获取不到响应信息

        3.3 了解OncePerRequestFilter

        Spring的OncePerRequestFilter类实际上是一个实现了Filter接口的抽象类。

        /**
         * Same contract as for {@code doFilter}, but guaranteed to be
         * just invoked once per request within a single request thread.
         * See {@link #shouldNotFilterAsyncDispatch()} for details.
         * 

        Provides HttpServletRequest and HttpServletResponse arguments instead of the * default ServletRequest and ServletResponse ones. */ protected abstract void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException; #通过上面的该方法的注释说明,可以发现OncePerRequestFilter过滤器保证一次请求只调用一次doFilterInternal方法;如内部的forward不会再多执行一次