【发布时间】:2014-02-14 19:31:16
【问题描述】:
修改来自 servlet 的 http 响应的最佳方法是什么?有人可以显示或链接一些样本吗?
【问题讨论】:
-
您可以访问
HttpServletResponse。使用它。
标签: jakarta-ee servlets filter response
修改来自 servlet 的 http 响应的最佳方法是什么?有人可以显示或链接一些样本吗?
【问题讨论】:
HttpServletResponse。使用它。
标签: jakarta-ee servlets filter response
您可以使用以下方法:
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.
【讨论】: