2014-02-14 75 views

回答

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. 
+0

另外,PrintWriter可以在運行中對其進行修改。假設你想刪除所有的'b'或類似的東西,只需要寫回來,而不寫。 –