I’ve created a class MyClass that intends to output a large amount of text to a JSP. Rather than having the MyClass object return a string to be displayed on the page, I figured it would be a better idea for the MyClass object to use the page’s output stream. Is this a good/possible idea?
In testing possible ways to do this…
These output the text, but it displays before the body of the page:
response.getWriter().append('test1'); response.getWriter().println('test2'); response.getWriter().write('test3');
This errors and tells me the output stream was already gotten:
response.getOutputStream().println('test4');
response.getWriter()will give you different writer than one used in JSP. If you want to write to same writer as JSP page is using, you need to useoutvariable from JSP page. Difference is that JSP uses buffering on top of standardresponse.getWriter(). That’s why you see your data written toresponse.getWriter()before JSP body.You cannot mix
response.getWriter()andresponse.getOutputStream().outvariable in JSP is JspWriter instance wrapping writer obtainedresponse.getWriter()so callingresponse.getOutputStream()will fail.What you should do in your JSP:
And in MyClass: