做的程序测试时经常出些问题,这回是:
发生在使用response.sendRedirect()方法的行,
很是莫名,于是搜索,得到解决办法:即在response.sendRedirect()
语句后增加return;语句即可。
引用http://topic.youkuaiyun.com/t/20040915/11/3374277.html的解释:
[quote]在response.sendRedirect之后,应该紧跟一句return;
我们已经知道response.sendRedirect是通过浏览器来做转向的,所以只有在页面处理完成后,才会有实际的动作。既然你已经要做转向了,那么后的输出还有什么意义呢?而且有可能会因为后面的输出导致转向失败。[/quote]
另得到另外一种会引起此异常的代码及解决方法:
引自http://hi.baidu.com/%E6%E4վ%B7羰/blog/item/74a9cc90362a8f8ba977a4be.html
[quote]抛出异常:
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">[/quote]
java.lang.IllegalStateException发生在使用response.sendRedirect()方法的行,
很是莫名,于是搜索,得到解决办法:即在response.sendRedirect()
语句后增加return;语句即可。
引用http://topic.youkuaiyun.com/t/20040915/11/3374277.html的解释:
[quote]在response.sendRedirect之后,应该紧跟一句return;
我们已经知道response.sendRedirect是通过浏览器来做转向的,所以只有在页面处理完成后,才会有实际的动作。既然你已经要做转向了,那么后的输出还有什么意义呢?而且有可能会因为后面的输出导致转向失败。[/quote]
另得到另外一种会引起此异常的代码及解决方法:
引自http://hi.baidu.com/%E6%E4վ%B7羰/blog/item/74a9cc90362a8f8ba977a4be.html
[quote]抛出异常:
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">[/quote]
本文介绍了解决Java中因使用response.sendRedirect()方法导致的java.lang.IllegalStateException异常的方法。一种解决方式是在redirect语句后添加return;另一种是处理输出流冲突问题,通过清除输出流和使用pageContext.pushBody()来避免异常。
635

被折叠的 条评论
为什么被折叠?



