getReader()/getInputStream() has already been called for this request

getReader()/getInputStream() has already been called for this request

项目中需要在filter对request中body中的数据进行处理,发现了这个问题
getRead() has already been called for this request/getInputStream() has already been called for this request
根本原因是
request中的getRead() 和 getInputStream()在读取一次后标记为-1,无法再次被读取
而可以看到@RequestBody在ServletServerHttpRequest中,也调用了getInputStream()方法
所以如果数据在filter中被读取,将无法在@RequestBody中再次读取。
此时解决方案,将request进行包装(装饰者模式),并重写getInputStream()和getRead()方法
public class ParamHttpServletRequestWrapper extends HttpServletRequestWrapper {

private final String body;

public ParamHttpServletRequestWrapper(HttpServletRequest request) throws IOException, ServletException {
    super(request);
    body = read(request);
}

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

@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();
        }
    };
}

private String read(HttpServletRequest request) throws IOException {
    BufferedReader bufferedReader = request.getReader();
    StringWriter writer = new StringWriter();
    write(bufferedReader, writer);
    return writer.getBuffer().toString();
}

private void write(Reader reader, Writer writer) throws IOException {
    int read;
    char[] buf = new char[1024 * 8];
    while ((read = reader.read(buf)) != -1) {
        writer.write(buf, 0, read);
    }
}

}

  • 0
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论

打赏作者

新来的前端

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值