解决spring 处理request.getInputStream()输入流只能读取一次问题
程序员文章站
2022-03-10 11:44:55
...
如果接口是用@RequestBody来接受数据,如果在拦截器中使用request.getInputStream() ,那么controller就无法拿到数据,会抛出错误:
java.lang.IllegalStateException: getInputStream() has already been called for this request
因为spring中request.getInputStream() 和request.getReader()只能被获取一次,而@RequestBody注解参数的底层实现也是通过流来获取请求参数的。
在springboot中解决方案如下:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ReqFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest reqs = (HttpServletRequest) req;
ServletRequest requestWrapper = null;
if (req instanceof HttpServletRequest) {
requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) req);
}
if (requestWrapper == null) {
chain.doFilter(req, response);
} else {
chain.doFilter(requestWrapper, response);
}
}
@Override
public void destroy() {
// Do nothing
}
@Override
public void init(FilterConfig config) throws ServletException {
// Do nothing
}
}
上一篇: C# WPF可拖拽的TabControl
下一篇: L1-003 个位数统计 (15分)