本地能获得post请求中的body,为什么打包成war包放在tomcat里就读不到body了?
时间: 2023-08-26 08:03:58 浏览: 159
浅析idea生成war包放入tomcat的路径访问问题
这个问题可能是由于Tomcat默认使用的是Servlet API的InputStream来读取请求体,而在读取完一次后就无法再读取一次,导致在读取一次后,后续的读取请求体中的数据就为空。
可以尝试使用HttpServletRequestWrapper来包装HttpServletRequest对象,在包装类中重写getReader()和getInputStream()方法来实现多次读取请求体中数据的需求。代码示例如下:
```java
public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
private final ByteArrayOutputStream cachedBytes;
public MultiReadHttpServletRequest(HttpServletRequest request) {
super(request);
cachedBytes = new ByteArrayOutputStream();
}
@Override
public ServletInputStream getInputStream() throws IOException {
if (cachedBytes.size() == 0) {
return super.getInputStream();
}
ByteArrayInputStream input = new ByteArrayInputStream(cachedBytes.toByteArray());
return new ServletInputStream() {
public int read() throws IOException {
return input.read();
}
};
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletRequest getRequest() {
return this;
}
public void cacheInputStream() throws IOException {
ServletInputStream inputStream = super.getInputStream();
byte[] bytes = IOUtils.toByteArray(inputStream);
cachedBytes.write(bytes);
}
public void resetInputStream() {
cachedBytes.reset();
}
}
```
使用时,可以在过滤器中对HttpServletRequest进行包装,如下所示:
```java
public class MultiReadFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (request.getContentType() != null && request.getContentType().contains("multipart/form-data")) {
chain.doFilter(request, response);
} else {
MultiReadHttpServletRequest multiReadHttpServletRequest = new MultiReadHttpServletRequest((HttpServletRequest) request);
multiReadHttpServletRequest.cacheInputStream();
chain.doFilter(multiReadHttpServletRequest, response);
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void destroy() {}
}
```
在web.xml文件中配置该过滤器即可实现多次读取请求体中数据的需求。
阅读全文