欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

解决spring 处理request.getInputStream()输入流只能读取一次问题

程序员文章站 2022-03-10 11:44:55
...

如果接口是用@RequestBody来接受数据,如果在拦截器中使用request.getInputStream() ,那么controller就无法拿到数据,会抛出错误:

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

因为springrequest.getInputStream() request.getReader()只能被获取一次,而@RequestBody注解参数的底层实现也是通过流来获取请求参数的。

springboot中解决方案如下:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ReqFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest reqs = (HttpServletRequest) req;
        ServletRequest requestWrapper = null;
        if (req instanceof HttpServletRequest) {
            requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) req);
        }
        if (requestWrapper == null) {
            chain.doFilter(req, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void destroy() {
        // Do nothing
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        // Do nothing
    }
}

 

相关标签: springboot