如何修改j2ee过滤器的http响应?

时间:2014-02-14 19:31:16

标签: java-ee servlets filter response

从servlet修改http响应的最佳方法是什么?有人可以展示或链接一些样品吗?

1 个答案:

答案 0 :(得分:1)

您可以使用以下方法:

HttpServletResponseWrapper :

javax.servlet.http.HttpServletResponseWrapper
Implements HttpServletResponse interface
Use this if you want to change the Response from a Servlet

Steps to modify the Response:

1. Create a response wrapper.
         – Extend HttpServletResponseWrapper.

2. Provide a PrintWriter that buffers output.
         – Override getWriter method to return a PrintWriter that saves everything sent to it and stores that result in a field.

3. Pass that wrapper to doFilter.
         – This call is legal because HttpServletResponseWrapper implements HttpServletResponse.

4. Extract and modify the output.
         – After call to doFilter method of the FilterChain, output of the original resource is available to you through whatever mechanism you provided in Step 2. Modify or replace it as appropriate.

5. Send the modified output to the client.
         – Original resource no longer sends output to client (output is stored in your response wrapper instead). You have to send the output. So, filter needs to obtain the PrintWriter or OutputStream from original response object and pass modified output to that stream.