ServletRequest中getReader()和getInputStream()只能调用一次的解决办法
程序员文章站
2022-03-10 12:10:18
...
public class HttpServletRequestReplacedFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
ServletRequest requestWrapper = null;
if (request instanceof HttpServletRequest) {
requestWrapper = new HttpServletRequestReplacedWrapper(
(HttpServletRequest) request);
}
if (requestWrapper == null) {
chain.doFilter(request, response);
} else {
chain.doFilter(requestWrapper, response);
}
}
@Override
public void destroy() {
}
}
public class HttpServletRequestReplacedWrapper extends
HttpServletRequestWrapper {
private final byte[] body; // 报文
public HttpServletRequestReplacedWrapper(HttpServletRequest request)
throws IOException {
super(request);
body = StreamUtils.copyToByteArray(request.getInputStream());
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return bais.read();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
};
}
}
上一篇: 批处理之for /r
下一篇: Localhost与数据库连接
推荐阅读
-
ServletRequest中getReader()和getInputStream()只能调用一次的解决办法
-
拦截器中,request中getReader()和getInputStream()只能调用一次,构建可重复读取inputStream的request.
-
解决request.getInputStream()与request.getReader()只能调用一次的问题
-
ServletRequest中getReader()和getInputStream()只能调用一次的解决办法
-
拦截器中,request中getReader()和getInputStream()只能调用一次,构建可重复读取inputStream的request.
-
关于web请求中的getInputStream()和getReader()只能读取一次的原因