今天写java验证码程序,完成后使用一切正常,可是总抛出java.lang.IllegalStateException异常,虽然并不影响正常使用,但看了总让人以为很不舒服,检查代码并无错,最后上网查了很多资料,终于发现缘由之所在。
咱们在作文件上传或者下载,或者过滤等操做时,可能要用到页面的输出流. 例如在JSP使用: response.reset(); response.setContentType(”application/vnd.ms-excel”); OutputStream os = response.getOutputStream(); 抛出异常: 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(); 就能够了; 2,不要在%][%之间写内容包括空格和换行符 3,在页面写入图片的时候,须要flush() OutputStream output=response.getOutputStream(); output.flush(); 4,在页面肯定写入<meta http-equiv=”Content-Type” content=”text/html; charset=gb2312”> 孙卫琴说多是tomcat的bug,我给她回了封信: :我看了看这里,http://www.javathinker.org/main.jsp?bc=showessay.jsp+filename=tomcat/tomcat_question_chapter13.htm这里是你回复别人的一个帖子,里面的观点基本上和我理解的同样,可是你最后写到多是tomcat的bug,我想解释一下:在jsp中,out是内嵌对象,即已经设置了PrintWriter out=response.getWriter();这样在再次getOutputStream()获得输出流时(好比转发过滤、下载文件时)就出错了(写排斥锁),我不止一次看到有人的文件下载页面在后台不断打印这个异常。而在servlet中没有默认out内置对象,因此没有出错.你能够在servlet中添加out对象试试,应该会报异常的.因此正确的处理方式就应该是:在servlet中作控制层,在业务处理之前不要得到out对象,当业务操做失败或出现异常时再生成out对象回显操做结果。 *********************************************************** response.getOutputStream() 和 requonse.getWriter() 区别 (1)使用tomcat5容器调用response.getOutputStream()方法便可实现,但调用requonse.getWriter()方法时,输出二进制数据时(图片等内容没法显示)则出现“getWriter() has already been called for this response”异常。 |