【问题标题】:How can you modify an http response from a j2ee filter? [closed]如何修改来自 j2ee 过滤器的 http 响应? [关闭]
【发布时间】:2014-02-14 19:31:16
【问题描述】:

修改来自 servlet 的 http 响应的最佳方法是什么?有人可以显示或链接一些样本吗?

【问题讨论】:

  • 您可以访问HttpServletResponse。使用它。

标签: jakarta-ee servlets filter response


【解决方案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.

【讨论】:

  • 另外,PrintWriter 可以动态修改它。假设你想删除所有的 'b' 或类似的东西,只需要写返回,不写。
猜你喜欢
  • 2020-07-21
  • 1970-01-01
  • 1970-01-01
  • 2014-01-18
  • 1970-01-01
  • 2015-06-20
  • 2014-08-18
  • 2019-01-20
  • 2021-02-13
相关资源
最近更新 更多