tags:

views:

856

answers:

2

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");
A: 

Have the class return you an iterator that generates the text one small chunk at a time. You could then iterate through the iterator in the JSP and print the data chunks at the appropriate location.

Akbar ibrahim
+5  A: 

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 use out variable from JSP page. Difference is that JSP uses buffering on top of standard response.getWriter(). That's why you see your data written to response.getWriter() before JSP body.

You cannot mix response.getWriter() and respnse.getOutputStream(). out variable in JSP is JspWriter instance wrapping writer obtained response.getWriter() so calling response.getOutputStream() will fail.

What you should do in your JSP:

<%
  new MyClass().writeToWriter(out);
%>

And in MyClass:

public void writeToWriter(Writer w) {
    w.println("My data appended to correct writer");
}
Peter Štibraný