您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

一次读取后,Http Servlet请求会丢失POST正文中的参数

一次读取后,Http Servlet请求会丢失POST正文中的参数

顺便说一句,解决此问题的另一种方法是不使用筛选器链,而是使用可以在已解析请求主体上运行的方面来构建自己的拦截器组件。由于您只需将请求InputStream转换为自己的模型对象一次,这样做也可能会更有效率。

但是,我仍然认为要多次读取请求正文是合理的,尤其是在请求通过过滤器链移动时。通常,我会将过滤器链用于要保留在HTTP层的某些操作,这些操作与服务组件分离。

正如Will Hartung所建议的那样,我是通过扩展HttpServletRequestWrapper,使用请求InputStream并实质上缓存字节来实现的。

public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
  private ByteArrayOutputStream cachedBytes;

  public MultiReadHttpServletRequest(HttpServletRequest request) {
    super(request);
  }

  @Override
  public ServletInputStream getInputStream() throws IOException {
    if (cachedBytes == null)
      cacheInputStream();

      return new CachedServletInputStream();
  }

  @Override
  public BufferedReader getReader() throws IOException{
    return new BufferedReader(new InputStreamReader(getInputStream()));
  }

  private void cacheInputStream() throws IOException {
    /* Cache the inputstream in order to read it multiple times. For
     * convenience, I use apache.commons IoUtils
     */
    cachedBytes = new ByteArrayOutputStream();
    IoUtils.copy(super.getInputStream(), cachedBytes);
  }

  /* An inputstream which reads the cached request body */
  public class CachedServletInputStream extends ServletInputStream {
    private ByteArrayInputStream input;

    public CachedServletInputStream() {
      /* create a new input stream from the cached request body */
      input = new ByteArrayInputStream(cachedBytes.toByteArray());
    }

    @Override
    public int read() throws IOException {
      return input.read();
    }
  }
}

现在,通过在过滤器链中传递原始请求之前,可以包装原始请求多次读取请求主体:

public class MyFilter implements Filter {
  @Override
  public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

    /* wrap the request in order to read the inputstream multiple times */
    MultiReadHttpServletRequest multiReadRequest = new MultiReadHttpServletRequest((HttpServletRequest) request);

    /* here I read the inputstream and do my thing with it; when I pass the
     * wrapped request through the filter chain, the rest of the filters, and
     * request handlers may read the cached inputstream
     */
    doMyThing(multiReadRequest.getInputStream());
    //OR
    anotherUsage(multiReadRequest.getReader());
    chain.doFilter(multiReadRequest, response);
  }
}

解决方案还将允许您通过这些getParameterXXX方法多次读取请求正文,因为底层调用getInputStream(),当然,它将读取缓存的请求InputStream

编辑

对于较新版本的ServletInputStream界面。您需要提供其他一些方法的实现,例如isReadysetReadListener等等。请参考下面的注释中提供的问题。

Jave 2022/1/1 18:23:51 有321人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶