title: How to substitute HttpServletResponse output stream?
body: <p>I need to use JSP to generate a HTML report. I made an example, but it does not work in Tomcat6 so far.</p>
  
  <pre><code>public class SubstitutionServlet extends HttpServlet {
      @Override
      protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/report.jsp");
          final ByteArrayOutputStream buf = new ByteArrayOutputStream();
          ServletResponseWrapper wrapper = new HttpServletResponseWrapper(response){
              @Override
              public PrintWriter getWriter() throws IOException {
                  return new PrintWriter(buf);
              }
          };
          dispatcher.forward(request, wrapper);
          String html = buf.toString("UTF-8"); // "" is returned
          System.out.println(html);
          response.getOutputStream().print("Completed");
      }
  }
  </code></pre>
  
  <p>When I try to run this example, I get an empty string as a result. What mistake have I made?</p>