java - How to substitute HttpServletResponse output stream? -
i need use jsp generate html report. made example, not work in tomcat6 far.
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"); // "" returned system.out.println(html); response.getoutputstream().print("completed"); } }
when try run example, empty string result. mistake have made?
the problem creating new printwriter
every invocation of method getwriter
. instead should have 1 , reuse it.
public class substitutionservlet extends httpservlet { private static final long serialversionuid = 1l; @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(); final printwriter out = new printwriter(buf); //create 1 writer servletresponsewrapper wrapper = new httpservletresponsewrapper(response) { @override public printwriter getwriter() throws ioexception { return out; // reuse writer } }; dispatcher.forward(request, wrapper); string html = buf.tostring("utf-8"); // "" returned system.out.println(html); response.getoutputstream().print("completed"); } }
Comments
Post a Comment