有的时候我们需要批量的修改Servlet中的响应的内容,这时候我们就可以通过HttpServletResponseWrapper
这个类,在Filter中先获取响应的内容,接着修改响应的内容,最后再把修改完之后的内容作为响应返回给客户端。代码如下演示:
1.创建一个继承自HttpServletResponseWrapper的类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import java.io.CharArrayWriter; import java.io.PrintWriter;
public class ResponseWrapper extends HttpServletResponseWrapper { private PrintWriter cachedWriter; private CharArrayWriter bufferedWriter;
public ResponseWrapper(HttpServletResponse response) { super(response); bufferedWriter = new CharArrayWriter(); cachedWriter = new PrintWriter(bufferedWriter); }
@Override public PrintWriter getWriter() { return cachedWriter; }
public String getResult() { return bufferedWriter.toString(); } }
|
2.在过滤器中修改响应的内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| package cn.iduoka.util.format;
import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter;
@WebFilter(filterName = "FormatFilter", urlPatterns = ("/")) public class FormatFilter implements Filter {
@Override public void destroy() {
}
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ResponseWrapper wrapper = new ResponseWrapper((HttpServletResponse) response); chain.doFilter(request, wrapper); String result = wrapper.getResult(); result = result.replace("</html>", "<div style='display: none;'>hello world</div>\n</html>"); response.setContentLength(-1); PrintWriter out = response.getWriter(); out.write(result); out.flush(); out.close(); }
@Override public void init(FilterConfig filterConfig) throws ServletException {
}
}
|
参考资料:servlet中使用HttpServletResponseWrapper截获返回的页面内容
本文链接:
https://www.nosuchfield.com/2016/03/29/gets-the-servlet's-response-and-modifies-its-contents/