java.lang.IllegalStateException: getOutputStream()

2020-01-29 10:30发布

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?

标签: java jsp
11条回答
2楼-- · 2020-01-29 10:59

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:

ServletOutputStream sos = response.getOutputStream();
sos.write(newHtml.getBytes("UTF8")); // newHtml is a String.
sos.flush();

It fixed this issue for me.

查看更多
孤傲高冷的网名
3楼-- · 2020-01-29 10:59

if you are facing this problem in servlets then while sending the response to the browser from servlet:

PrintWriter out=response.getWriter();

This should be the first statement aftter that you can write your html code in servlet that is eventually send to the browser

查看更多
我想做一个坏孩纸
4楼-- · 2020-01-29 11:02

Turn view_image.jsp into a Servlet mapped to ViewImage and call it like

<img src='<%= request.getContextPath() %>/ViewImage?pat_acc=<%=Pat_Acct%>' style='position: absolute; left: 0pt; top: 0px;' "/> 

in your JSP file.

查看更多
够拽才男人
5楼-- · 2020-01-29 11:04

In Spring, you can solve this issue changing

            response.getOutputStream().write(cabecera.getBytes());

to

            response.getWriter().write(cabecera);
查看更多
相关推荐>>
6楼-- · 2020-01-29 11:07

Try this, it is not the best of solutions though, but it works.

in.close();
out2.flush();
out.clear();
out = pageContext.pushBody(); 

Where 'in' is the InputStream (if you are using it), 'out2' is the new response.getOutputStream() and 'out' is the default JspWriter.

查看更多
虎瘦雄心在
7楼-- · 2020-01-29 11:11

try remove all template texts from jsp file. for example,

1 <%@
2    ....
3 %>
4 <%
5    ....
6 %>

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.

查看更多
登录 后发表回答