title: Looking for an example for inserting content into the response using a servlet filter
body: <p>I've been searching the net and stackoverflow for an example of somebody inserting content into the response using a servlet filter, but can only find examples of people capturing/compressing the output and/or changing the headers. My goal is to append a chunk of HTML just before the closing &#60;/body&#62; of all HTML responses.</p>
  
  <p>I'm working on a solution that extends the HttpServletResponseWrapper to use my own PrintWriter, then overriding the write methods thereon. Inside the write method I'm storing the last 7 characters to see if it's equal to the closing body tag, and then I write my HTML chunk plus the closing body tag, before continuing normal write operations for the rest of the document.</p>
  
  <p>I feel that somebody must have solved this problem already, and probably more elegantly than I will. I'd appreciate any examples of how to use a servlet filter to insert content into a response.</p>
  
  <p>UPDATED</p>
  
  <p>Responding to a comment, I am also trying to implement the CharResponseWrapper from <a href="http://www.oracle.com/technetwork/java/filters-137243.html" rel="noreferrer">http://www.oracle.com/technetwork/java/filters-137243.html</a>. Here is my code:</p>
  
  <pre><code>PrintWriter out = response.getWriter();
  CharResponseWrapper wrappedResponse = new CharResponseWrapper(
          (HttpServletResponse)response);
  
  chain.doFilter(wrappedRequest, wrappedResponse);
  String s = wrappedResponse.toString();
  
  if (wrappedResponse.getContentType().equals("text/html") &amp;&amp;
          StringUtils.isNotBlank(s)) {
      CharArrayWriter caw = new CharArrayWriter();
      caw.write(s.substring(0, s.indexOf("&lt;/body&gt;") - 1));
      caw.write("WTF&lt;/body&gt;&lt;/html&gt;");
      response.setContentLength(caw.toString().length());
      out.write(caw.toString());
  }
  else {
      out.write(wrappedResponse.toString());
  }
  
  out.close();
  </code></pre>
  
  <p>I am also wrapping the request, but that code works and shouldn't affect the response.</p>