论坛首页 Java企业应用论坛

记录开发问题:java.lang.IllegalStateException异常

浏览 7272 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-11-14  
做的程序测试时经常出些问题,这回是:

java.lang.IllegalStateException


发生在使用response.sendRedirect()方法的行,

很是莫名,于是搜索,得到解决办法:即在response.sendRedirect()

语句后增加return;语句即可。

引用http://topic.csdn.net/t/20040915/11/3374277.html的解释:

引用
在response.sendRedirect之后,应该紧跟一句return;  
  我们已经知道response.sendRedirect是通过浏览器来做转向的,所以只有在页面处理完成后,才会有实际的动作。既然你已经要做转向了,那么后的输出还有什么意义呢?而且有可能会因为后面的输出导致转向失败。


另得到另外一种会引起此异常的代码及解决方法:

引自http://hi.baidu.com/%E6%E4վ%B7羰/blog/item/74a9cc90362a8f8ba977a4be.html

引用
抛出异常:
ERROR [Engine] StandardWrapperValve[jsp]: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
综合分析原因如下:
这是web容器生成的servlet代码中有out.write(””),这个和JSP中调用的response.getOutputStream()产生冲突.
即Servlet规范说明,不能既调用 response.getOutputStream(),又调用response.getWriter(),无论先调用哪一个,在调用第二个时候应会抛出 IllegalStateException,因为在jsp中,out变量是通过response.getWriter得到的,在程序中既用了response.getOutputStream,又用了out变量,故出现以上错误。
解决方案:
1.在程序中添加:
out.clear();
out = pageContext.pushBody();
就可以了;

我是在页面输出图片之后写的这两句,代码如下:

//输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());

out.clear();
out = pageContext.pushBody();



2,不要在%][%之间写内容包括空格和换行符
3,在页面写入图片的时候,需要flush()
 OutputStream output=response.getOutputStream();
 output.flush();
4,在页面确定写入<meta http-equiv="Content-Type" content="text/html;charset=GB18030">
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics