我认为,当它到达响应得到承诺
ServletFilter A的
Step4。提交响应后,即将标头写入客户端,便无法执行需要添加标头的操作。这些操作类似于添加cookie。
如果您不希望在提交
Step4包装之前
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(); }}}


