1 回答
TA贡献1831条经验 获得超10个赞
最后我想通了,所以我会在这里留下一些简单但有用的建议给其他人。我使用了一个请求包装器,但为了使其正常工作,我添加了一个最高阶的过滤器,以便在开始执行拦截器之前将每个请求包装到包装器中。现在它运行良好;) 这是最重要的代码 - 过滤器将每个请求包装到多读包装器中(拦截器看起来与上面几乎相同,包装器不是我发明的,在堆栈中找到,我发现它最清晰易读):
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalWrapFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
MultiReadRequest wrapper = new MultiReadRequest((HttpServletRequest) request);
chain.doFilter(wrapper, response);
}
@Override
public void destroy() {
}
class MultiReadRequest extends HttpServletRequestWrapper {
private String requestBody;
public MultiReadRequest(HttpServletRequest request) {
super(request);
try {
requestBody = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(requestBody.getBytes());
return new ServletInputStream() {
@Override
public boolean isFinished() {
return byteArrayInputStream.available() == 0;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream(), Charset.forName("UTF-8")));
}
}
}
添加回答
举报