我认为响应在到达时会做出ServletFilter A
承诺Step 4
。一旦响应提交,即标头被写入客户端,您将无法进行需要添加标头的操作。添加cookies之类的操作。
如果您希望在Step 4
尝试包装HttpServletResponse
并返回自定义输出流之前不提交响应,该输出流缓冲数据直到它到达step 4
然后提交响应。
这是示例代码:
public class ResponseBufferFilter implements Filter
{
public void init(FilterConfig filterConfig) throws ServletException
{
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException
{
HttpServletResponse httpResponse = (HttpServletResponse)response;
BufferResponseWrapper wrapper = new BufferResponseWrapper(httpResponse);
filterChain.doFilter(request, resposneWrapper);
response.getOutputStream().write(wrapper .getWrapperBytes());
}
public void destroy()
{
}
private final class BufferResponseWrapper extends HttpServletResponseWrapper
{
MyServletOutputStream stream = new MyServletOutputStream();
public BufferResponseWrapper(HttpServletResponse httpServletResponse)
{
super(httpServletResponse);
}
public ServletOutputStream getOutputStream() throws IOException
{
return stream;
}
public PrintWriter getWriter() throws IOException
{
return new PrintWriter(stream);
}
public byte[] getWrapperBytes()
{
return stream.getBytes();
}
}
private final class MyServletOutputStream extends ServletOutputStream
{
private ByteArrayOutputStream out = new ByteArrayOutputStream();
public void write(int b) throws IOException
{
out.write(b);
}
public byte[] getBytes()
{
return out.toByteArray();
}
}
}