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

问题:

查阅资料后得知:在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类拿到每个参数值了;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值