当前位置:   article > 正文

java stream 多次读取_ServletInputStream的重复读取(多次读取)(转)

servletinputstream多次读取

在使用Servlet进行Web开发的时候,有时候为了增加必要的业务处理而又不想修改现有的程序,往往采用Filter。这样在各个Filter中可能都要读取ServletInputStream流的内容,而ServletInputStream却只能读一次,这时候必须备份HttpServleRequest。

class BufferedServletInputStream extends ServletInputStream {

private ByteArrayInputStream inputStream;

public BufferedServletInputStream(byte[] buffer) {

this.inputStream = new ByteArrayInputStream( buffer );

}

@Override

public int available() throws IOException {

return inputStream.available();

}

@Override

public int read() throws IOException {

return inputStream.read();

}

@Override

public int read(byte[] b, int off, int len) throws IOException {

return inputStream.read( b, off, len );

}

}

class BufferedServletRequestWrapper extends HttpServletRequestWrapper {

private byte[] buffer;

public BufferedServletRequestWrapper(HttpServletRequest request) throws IOException {

super( request );

InputStream is = request.getInputStream();

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte buff[] = new byte[ 1024 ];

int read;

while( ( read = is.read( buff ) ) > 0 ) {

baos.write( buff, 0, read );

}

this.buffer = baos.toByteArray();

}

@Override

public ServletInputStream getInputStream() throws IOException {

return new BufferedServletInputStream( this.buffer );

}

}

在Filter的doFilter()或者Servlet的doPost()中,

//备份HttpServletRequest

HttpServletRequest httpRequest = (HttpServletRequest)request;

httpRequest = new BufferedServletRequestWrapper( httpRequest );

//使用流

InputStream is = request.getInputStream();

//其他业务逻辑

//将request 传到下一个Filter

chain.doFilter(request, response);

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/550888
推荐阅读
相关标签
  

闽ICP备14008679号