I get the following exception when I'm trying to request loading images from server on client side:
241132533 [TP-Processor1] ERROR [/jspapps].[jsp] - Servlet.service() for servlet jsp threw exception java.lang.IllegalStateException: getOutputStream() has already been called for this response
Can any one explain this exception to me and also how to get over it?
I just encountered the same problem in my recent work.
We have a servlet filter in which we use ServletResponse.getWriter() method to write the body, and in some Spring MVC controller, we also use response.getOutputStream() to write something like images(array of bytes) into body.
Since every request will go through filter, and based on Java API doc:
"Either this method(getWriter()) or getOutputStream() may be called to write the body, not both."
That's the reason why we got the "java.lang.IllegalStateException: getOutputStream() has already been called for this response" exception.
So in that filter, I changed the code to:
It fixed this issue for me.
if you are facing this problem in servlets then while sending the response to the browser from servlet:
This should be the first statement aftter that you can write your html code in servlet that is eventually send to the browser
Turn view_image.jsp into a Servlet mapped to
ViewImage
and call it likein your JSP file.
In Spring, you can solve this issue changing
to
Try this, it is not the best of solutions though, but it works.
Where 'in' is the InputStream (if you are using it), 'out2' is the new
response.getOutputStream()
and 'out' is the defaultJspWriter
.try remove all template texts from jsp file. for example,
there is a '\n' between line 3 and 4, and it is treated as template text, response.getWriter() is called to write that '\n' to client. after line 6, there could be invisible whitespaces too which will screwup the outputstream. but line 5 can
return
early to avoid that.