1 public class CustomPrintWriter extends PrintWriter{ 2 private StringBuilder buffer; 3 4 public CustomPrintWriter(Writer out) { 5 super(out); 6 buffer = new StringBuilder(); 7 } 8 9 @Override 10 public void write(char[] buf, int off, int len) { 11 char[] dest = new char[len]; 12 System.arraycopy(buf,off,dest,0,len);//深复制字符数组 13 buffer.append(dest); 14 } 15 16 public String getContent() { 17 return buffer.toString(); 18 } 19 }
CustomResponseWrapper.java (重写HttpServletResponseWrapper方法)
1 public class CustomResponseWrapper extends HttpServletResponseWrapper{ 2 private CustomPrintWriter customPrintWriter; 3 4 public CustomResponseWrapper(HttpServletResponse response) { 5 super(response); 6 } 7 8 @Override 9 public PrintWriter getWriter() throws IOException { 10 customPrintWriter = new CustomPrintWriter(super.getWriter()); 11 return customPrintWriter; 12 } 13 14 public CustomPrintWriter getCustomPrintWriter() { 15 return customPrintWriter; 16 } 17 }
ResponseFilter.java (过滤器)
1 public class ResponseFilter implements Filter{ 2 public void init(FilterConfig filterConfig) throws ServletException {} 3 4 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 5 CustomResponseWrapper customResponseWrapper = new CustomResponseWrapper((HttpServletResponse) servletResponse); 6 filterChain.doFilter(servletRequest,customResponseWrapper);//转发请求获取请求返回结果 7 CustomPrintWriter writer = customResponseWrapper.getCustomPrintWriter();//获取请求的返回结果 8 if(writer != null){ 9 String content = writer.getContent(); 10 /** 11 * 在不修改jsp源码的情况下修改展示内容 12 */ 13 content = content.replace("XXX", LoginCheckServlet.username); 14 servletResponse.getWriter().write(content); 15 } 16 } 17 18 public void destroy() {} 19 }