Is it possible to forward or redirect from a servlet filter after the response has been committed?

瘦欲@ 提交于 2019-11-30 14:28:09

The "committed" status of an HttpServletResponse is really a way of saying whether the response headers have been written to the underlying socket. A "committed" response has had (at least) the first line written. Since the first line of the response contains the status code, it follows that you cannot change the status code of a committed response ... and that means it is too late to change the status to 3xx to do a redirect. Similarly, you cannot do a local forward because you've already started sending the response.

shams

You can achieve what you want by using a custom HttpServletResponse. You pass this wrapped HttpServletResponse down the filter chain. You can provide a local OutputStream that stores all the write requests, local variables to store the status code and headers. Once you are back in your filter you can then decide to perform the redirect or copy back the results from the local variables from the wrapper into the original ServletResponse (i.e. set the status code and header and copy the results from the local output stream into the servlet response's output stream).

Edit:

Refer to the Programming Customized Requests and Responses section for a code example which uses a CharResponseWrapper. The example uses a custom Writer, but it can be easily extended to an OutputStream. Based on how your Servlet is used, you need to override one or both of getWriter() and getOutputStream() to delay committing anything onto the original response. In addition, you will need to override isCommitted() to return false, so that the forward can be executed at any time down the filter chain. You will also need to override resetBuffer() to initialize a new OutputStream/Writer to store the new content (including headers) after the redirect/forward.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!