java.lang.IllegalStateException:已经为此响应调用了 getOutputStream()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3540464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.lang.IllegalStateException: getOutputStream() has already been called for this response
提问by ama
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
241132533 [TP-Processor1] 错误 [/jspapps].[jsp] - servlet jsp 的 Servlet.service() 抛出异常 java.lang.IllegalStateException: getOutputStream() 已被调用用于此响应
Can any one explain this exception to me and also how to get over it?
任何人都可以向我解释这个例外以及如何克服它?
回答by BalusC
can any one explain this exception to me
任何人都可以向我解释这个例外吗
You're attempting to write binary data to response.getOutputStream()
using raw Java code inside a JSP file which itself is already using response.getWriter()
to write any template text. See also the Throwspart of the linked javadocs.
您正在尝试response.getOutputStream()
使用 JSP 文件中的原始 Java 代码编写二进制数据,该文件本身已response.getWriter()
用于编写任何模板文本。另请参阅链接的 javadoc的Throws部分。
and also how to get over it?
以及如何克服它?
Write Java code in a real Java class instead. Create a class which extends
HttpServlet
, move all that Java code to there, map it in web.xml
and change the request URL to call the servlet instead.
而是在真正的 Java 类中编写 Java 代码。创建一个类extends
HttpServlet
,将所有 Java 代码移到那里,将其映射到其中web.xml
并更改请求 URL 以调用 servlet。
See also:
也可以看看:
回答by Behrang Saeedzadeh
Turn view_image.jsp into a Servlet mapped to ViewImage
and call it like
将 view_image.jsp 变成一个映射到的 ServletViewImage
并像这样调用它
<img src='<%= request.getContextPath() %>/ViewImage?pat_acc=<%=Pat_Acct%>' style='position: absolute; left: 0pt; top: 0px;' "/>
in your JSP file.
在您的 JSP 文件中。
回答by irreputable
try remove alltemplate texts from jsp file. for example,
尝试从 jsp 文件中删除所有模板文本。例如,
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.
第 3 行和第 4 行之间有一个 '\n',它被视为模板文本,调用 response.getWriter() 将该 '\n' 写入客户端。在第 6 行之后,也可能有不可见的空格,这会弄乱输出流。但是第 5 行可以return
提前避免这种情况。
回答by Soundlink
Make sure eliminating all output in your view_image.jsp
. Simple line breaks can be responsible for generating output.
确保消除view_image.jsp
. 简单的换行符可以负责生成输出。
For example, if you have these declarions...
例如,如果您有这些声明...
<%@ page import ... %>
<%@ page import ... %>
... you should write them this way
...你应该这样写
<%@ page import ... %><%@ page import ... %><%
...%>
If you take a look to the compiled servlet code you shouldn't see out.write("\r\n")
before your image response.
如果您查看已编译的 servlet 代码,您不应该out.write("\r\n")
在图像响应之前看到。
A better way would be to change your view_image.jsp
into a Servlet, but if you can't do that, removing the line breaks in the jsp is a workaround.
更好的方法是将您的更改view_image.jsp
为 Servlet,但如果您不能这样做,则删除 jsp 中的换行符是一种解决方法。
回答by Harke
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
.
其中 'in' 是 InputStream(如果您正在使用它),'out2' 是新的response.getOutputStream()
,'out' 是默认的JspWriter
。
回答by Josef Hammer
I just stumbled upon this old question as I had the same issue. In the end it was quite easy to get rid of the exception: Just call out.clear()
before:
我只是偶然发现了这个老问题,因为我有同样的问题。最后很容易摆脱异常:只需调用out.clear()
之前:
out.clear();
...
// later, in a different method
ServletOutputStream out = response.getOutputStream();
...
out.clear()
also helped me to get rid of all those empty lines from <%@page import=...
and the like.
out.clear()
还帮助我摆脱了所有那些空行<%@page import=...
等等。
回答by Surendra
<%@page import="java.sql.DriverManager"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%
Connection con=null;
ResultSet rs = null;
Statement st = null;
String sql = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("test","root","root");
st = con.createStatement();
sql = "select image from projects where projectid='1'";
System.out.println(sql);
rs = st.executeQuery(sql);
String imgLen = "";
out.clear();
while (rs.next())
{
imgLen = rs.getString(1);
System.out.println(imgLen.length());
int len = imgLen.length();
byte[] rb = new byte[len];
InputStream readImg = rs.getBinaryStream(1);
int index = readImg.read(rb, 0, len);
response.reset();
response.setContentType("image/jpg");
response.getOutputStream().write(rb, 0, len);
response.getOutputStream().flush();
response.getOutputStream().close();
}
st.close();
rs.close();
if (true) return;
} catch (Exception e) {e.printStackTrace();}
%>
回答by Yan Yan
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.
我们有一个 servlet 过滤器,其中我们使用 ServletResponse.getWriter() 方法来写入正文,并且在某些 Spring MVC 控制器中,我们还使用 response.getOutputStream() 将图像(字节数组)之类的内容写入正文。
Since every request will go through filter, and based on Java API doc:
由于每个请求都将通过过滤器,并且基于 Java API 文档:
"Either this method(getWriter()) or getOutputStream() may be called to write the body, not both."
“可以调用此方法 (getWriter()) 或 getOutputStream() 来写入正文,而不是同时调用两者。”
That's the reason why we got the "java.lang.IllegalStateException: getOutputStream() has already been called for this response" exception.
这就是我们得到“java.lang.IllegalStateException: getOutputStream() has been called for this response”异常的原因。
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.
它为我解决了这个问题。
回答by Jorge Gutiérrez Parejo
In Spring, you can solve this issue changing
在 Spring 中,您可以通过更改解决此问题
response.getOutputStream().write(cabecera.getBytes());
to
到
response.getWriter().write(cabecera);
回答by 3AK
I had this code and fixed it like this:
我有这个代码并像这样修复它:
@RequestMapping(value = "xyz", method = RequestMethod.POST)
public String generateReport(HttpServletResponse response, @Valid @ModelAttribute Form form, Errors errors, Model model) {
if (errors.hasErrors()) {
model.addAttribute(form);
return "abcd/xyz";
} else {
someMethodWhichUsesResponse(response);
}
Earlier:
return "abcd/xyz";
Fixed by:
return null;
}
I returned null because, from this method, I was expecting a download. As per the explanation given here, I fixed my problem.
我返回 null 因为,从这个方法,我期待下载。根据这里给出的解释,我解决了我的问题。