HttpServletResponseWrapper包装HttpServletResponse 后无法正常响应
目的想通过过滤器修改响应中的参数,发现包装后无法正常响应,从浏览器请求后浏览器一直在转圈圈持续很久HttpServletResponseWrapperpublic class Response2Wrapper extends HttpServletResponseWrapper {private ByteArrayOutputStream output;private ServletOutputS
·
目的想通过过滤器修改响应中的参数,发现包装后无法正常响应,从浏览器请求后浏览器一直在转圈圈持续很久
HttpServletResponseWrapper
public class Response2Wrapper extends HttpServletResponseWrapper {
private ByteArrayOutputStream output;
private ServletOutputStream filterOutput;
public Response2Wrapper(HttpServletResponse response) {
super(response);
output = new ByteArrayOutputStream();
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (filterOutput == null) {
filterOutput = new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
output.write(b);
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setWriteListener(WriteListener writeListener) {
}
};
}
return filterOutput;
}
public byte[] toByteArray() {
return output.toByteArray();
}
}
ServletParamaterFilter
public class ServletParamaterFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
System.out.println("=====ServletParamaterFilter=====");
//转换成代理类
Response2Wrapper wrapperResponse = new Response2Wrapper((HttpServletResponse) response);
// 这里只拦截返回,直接让请求过去,如果在请求前有处理,可以在这里处理
chain.doFilter(request, wrapperResponse);
PrintWriter out = response.getWriter();
//response.setContentLength("test".getBytes().length);
out.write("test");
out.flush();
out.close();
} else {
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig filterConfig) {
System.out.println("ServletParamaterFilter初始化创建....");
}
}
通过不短的查找调试,原来是没有给包装后的response设置对应的内容长度
response.setContentLength("test".getBytes().length);
问题解决
更多推荐
已为社区贡献2条内容
所有评论(0)