Bootstrap

Filter 重复读取 request 的POST请求参数

需求:

​ 在Filter中获取POST请求参数只能调用request.getInputStream()request.getReader()的方式把请求体读出来,可是会抛出如下异常:

java.lang.IllegalStateException: getReader() has already been called for this request

原因:

request请求体只能读取一次,多次读取会抛异常,在过滤器中读取的话,在Controller中再拿请求体的字节流的时候就会抛异常。

解决方案:

继承 HttpServletRequestWrapper,复制请求体,定制getInputStream()、getReader()方法。

注意: 请求由外到内分别经过:Filter->Servlet->Interceptor->Aspect->Controller;这意味着:

  • Servlet层开始调用request.getInputStream()只有Filter层可以进行请求体复制的操作
  • Servlet层开始进行注解的操作Filter层拿不到自定义的注解

代码实现:

OperateLogFilter.java

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * <p> @Title OperateLogFilter
 * <p> @Description 操作日志记录
 *
 * @author ACGkaka
 * @date 2021/6/25 9:20
 */
@Component
public class OperateLogFilter implements Filter {

    private final Logger log = LoggerFactory.getLogger(OperateLogFilter.class);

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (servletRequest instanceof HttpServletRequest) {
            MyRequestWrapper requestWrapper = new MyRequestWrapper((HttpServletRequest) servletRequest);
            String requestBody;
            if ("GET".equals(requestWrapper.getMethod())) {
                requestBody = JSONObject.toJSONString(requestWrapper.getParameterMap());
            } else {
                requestBody = requestWrapper.getBody();
            }
            requestBody = requestBody.replaceAll("\r\n", "");
            requestBody = requestBody.replaceAll(" {2}", " ");
            log.info("requestBody: " + requestBody);
            filterChain.doFilter(requestWrapper, servletResponse);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}

MyRequestWrapper.java

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/**
 * <p> @Title MyRequestWrapper
 * <p> @Description 定制请求
 *
 * @author ACGkaka
 * @date 2021/6/24 19:34
 */
public class MyRequestWrapper extends HttpServletRequestWrapper {

    /** 每次读取8kb */
    private static final int BUFFER_SIZE = 1024 * 8;

    /** 请求体 */
    private final String body;

    /**
     * 构造方法
     */
    public MyRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        BufferedReader reader = request.getReader();
        StringWriter writer = new StringWriter();
        int read;
        char[] buf = new char[BUFFER_SIZE];
        while( ( read = reader.read(buf) ) != -1 ) {
            writer.write(buf, 0, read);
        }
        this.body = writer.getBuffer().toString();
    }

    /**
     * 获取请求体
     *
     * @return 请求体
     */
    public String getBody() {
        return body;
    }

    @Override
    public ServletInputStream getInputStream()  {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes());
        return new ServletInputStream() {

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

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

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read(){
                return bais.read();
            }
        };
    }

    @Override
    public BufferedReader getReader(){
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

}

FilterConfig.java

import cn.demo.project.common.filter.AccessTokenFilter;
import cn.demo.project.common.filter.ExceptionFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <p> @Title FilterConfig
 * <p> @Description 过滤器配置类
 *
 * @author ACGkaka
 * @date 2021/6/16 18:08
 */
@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean OperateLogFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.addUrlPatterns("/*");
        registration.setFilter(new AccessTokenFilter());
        registration.setName("OperateLogFilter");
        registration.setOrder(1);
        return registration;
    }
}

悦读

道可道,非常道;名可名,非常名。 无名,天地之始,有名,万物之母。 故常无欲,以观其妙,常有欲,以观其徼。 此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。

;