springboot中filter获取了body,导致controller无法获取body,如何解决
时间: 2023-11-30 07:05:04 浏览: 156
在Spring Boot中,HTTP请求的Body只能被读取一次,因此如果Filter已经读取了Body,那么Controller就无法再次读取Body了。为了解决这个问题,可以使用HttpServletRequestWrapper来包装HttpServletRequest,从而在Filter中读取Body后,仍然可以将HttpServletRequest传递给Controller。
以下是一个示例代码:
```java
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
private final byte[] body;
public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
body = IOUtils.toByteArray(request.getInputStream());
}
@Override
public ServletInputStream getInputStream() throws IOException {
return new ServletInputStreamWrapper(body);
}
@Override
public BufferedReader getReader() throws IOException {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
return new BufferedReader(new InputStreamReader(byteArrayInputStream));
}
}
```
然后,在Filter中使用BodyReaderHttpServletRequestWrapper来包装HttpServletRequest:
```java
public class BodyReaderFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
BodyReaderHttpServletRequestWrapper requestWrapper = new BodyReaderHttpServletRequestWrapper(httpServletRequest);
chain.doFilter(requestWrapper, response);
}
}
```
这样,在Controller中就可以正常获取到请求的Body了。
阅读全文