java通过inpuStram获取到request的请求流后Controller拿不到参数了

2023-01-19 12:59:38

问题:

查阅资料后得知:在Spring中request的只能被获取一次,拦截器获取之后就会导致Controller拿不到值,因为我写了个拦截器,去拦截获取的参数,对参数进行校验加密(也就是上一篇的防篡改功能),然后拦截器验证没问题,controller获取的json类型的数据却是空的

解决办法

写过滤器重新把流再塞回去

1.创建个类,为了备份request中的值

public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {
 
    private final byte[] buff;
 
    public MyHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        InputStream is = request.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = is.read(b)) != -1) {
            baos.write(b, 0, len);
        }
        buff = baos.toByteArray();
    }
 
    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(buff);
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return bais.read();
            }
        };
    }
 
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }
}

2.创建一个Filter,将该拦截器配置在项目中,为了调用备份的HttpServletRequestWrapper


public class MyRequestBodyFilter implements Filter {
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
 
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        servletRequest = new MyHttpServletRequestWrapper(httpServletRequest);
        filterChain.doFilter(servletRequest, servletResponse);
    }
 
    @Override
    public void destroy() {
 
    }
}

3.创建一个工具类,在拦截器中获取request的值

public class RequestUtils {
 
    public static String getRequestValue(HttpServletRequest request) throws IOException {
        StringBuffer sb = new StringBuffer();
        MyHttpServletRequestWrapper myHttpServletRequestWrapper = new MyHttpServletRequestWrapper(request);
        InputStream is = myHttpServletRequestWrapper.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String str;
        while ((str = br.readLine()) != null) {
            sb.append(str);
        }
        return sb.toString();
    }
 
}

当以上创建过后,写的SignAuthInterceptor类就可以正常进行验证防篡改功能了,并且通过request获取的流,也可以通过Controller类拿到每个参数值了;

  • 作者:weijx_
  • 原文链接:https://blog.csdn.net/weijx_/article/details/114020230
    更新时间:2023-01-19 12:59:38