getOutputStream()异常的原因和解决方法

 

getOutputStream()异常的原因和解决方法

tomcat5下jsp出现getOutputStream() has already been called for this response异常的原因和解决方法

在tomcat5下jsp中出现此错误一般都是在jsp中使用了输出流(如输出图片验证码,文件下载等),
没有妥善处理好的原因。

具体的原因就是
在tomcat中jsp编译成servlet之后在函数_jspService(HttpServletRequest request, HttpServletResponse response)的最后
有一段这样的代码
finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
    }
这里是在释放在jsp中使用的对象,会调用response.getWriter(),因为这个方法是和
response.getOutputStream()相冲突的!所以会出现以上这个异常。

然后当然是要提出解决的办法,其实挺简单的(并不是和某些朋友说的那样--
将jsp内的所有空格和回车符号所有都删除掉),

在使用完输出流以后调用以下两行代码即可:

Java代码 复制代码
  1. out.clear();   
  2. out = pageContext.pushBody();  


最后这里是一个输出彩色验证码例子(这样的例子几乎随处可见)
imag.jsp


Java代码 复制代码
  1. <% @ page   import = " java.awt.*,java.awt.image.*,java.util.*,javax.imageio.* "   %>    
  2. <% @ page  import = " java.io.OutputStream "   %>    
  3. <%!    
  4. Color getRandColor( int  fc, int  bc){   
  5. Random random  =   new  Random();   
  6. if (fc > 255 ) fc = 255 ;   
  7. if (bc > 255 ) bc = 255 ;   
  8. int  r = fc + random.nextInt(bc - fc);   
  9. int  g = fc + random.nextInt(bc - fc);   
  10. int  b = fc + random.nextInt(bc - fc);   
  11. return   new  Color(r,g,b);   
  12. }   
  13. %>    
  14. <%    
  15. try {   
  16. response.setHeader( " Pragma " , " No-cache " );   
  17. response.setHeader( " Cache-Control " , " no-cache " );   
  18. response.setDateHeader( " Expires " ,  0 );   
  19. int  width = 60 , height = 20 ;   
  20. BufferedImage image  =   new  BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);   
  21. OutputStream os = response.getOutputStream();   
  22. Graphics g  =  image.getGraphics();   
  23. Random random  =   new  Random();   
  24. g.setColor(getRandColor( 200 , 250 ));   
  25. g.fillRect( 0 ,  0 , width, height);   
  26.   
  27. g.setFont( new  Font( " Times New Roman " ,Font.PLAIN, 18 ));   
  28. g.setColor(getRandColor( 160 , 200 ));   
  29. for  ( int  i = 0 ;i < 155 ;i ++ )   
  30. {   
  31. int  x  =  random.nextInt(width);   
  32. int  y  =  random.nextInt(height);   
  33. int  xl  =  random.nextInt( 12 );   
  34. int  yl  =  random.nextInt( 12 );   
  35. g.drawLine(x,y,x + xl,y + yl);   
  36. }   
  37. String sRand = "" ;   
  38. for  ( int  i = 0 ;i < 4 ;i ++ ){   
  39. String rand = String.valueOf(random.nextInt( 10 ));   
  40. sRand += rand;   
  41. g.setColor( new  Color( 20 + random.nextInt( 110 ), 20 + random.nextInt( 110 ), 20 + random.nextInt( 110 )));   
  42. g.drawString(rand, 13 * i + 6 , 16 );   
  43. }   
  44. session.setAttribute( " rand " ,sRand);   
  45. g.dispose();   
  46.   
  47. ImageIO.write(image,  " JPEG " ,os);   
  48. os.flush();   
  49. os.close();   
  50. os = null ;   
  51. response.flushBuffer();   
  52. out.clear();   
  53. out  =  pageContext.pushBody();   
  54. }   
  55. catch (IllegalStateException e)   
  56. {   
  57. System.out.println(e.getMessage());   
  58. e.printStackTrace();   
  59. } %>   

来自:http://jessdy.javaeye.com/blog/187448

 

 

  1. 原始代码:
  2. <%@ page contentType="text/html; charset=GBK" %>
  3. <%@ page autoFlush="false" %>
  4. <%@ page import="java.sql.*" %>
  5. <%@ page import="java.io.*" %>
  6. <%@ page import="java.util.*" %>
  7. <%@ page import="java.awt.*" %>
  8. <%@ page import="java.awt.image.*" %>
  9. <%@ page import="com.sun.image.codec.jpeg.*" %>
  10. <%@ page import="com.sun.image.codec.jpeg.*" %>
  11. <%@ page import="com.csland.common.util.*" %>
  12. <%!
  13. public void noImg(ServletOutputStream outStream){
  14.   try{
  15.         int width=80, height=50;
  16.         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  17.         Graphics g = image.getGraphics();
  18.         //以下填充背景颜色  
  19.         g.setColor(Color.WHITE);
  20.         g.fillRect(00, width, height);
  21.         g.setColor(Color.ORANGE);
  22.         g.drawRect(00, width-1, height-1);
  23.         String random="random";
  24.         //以下设置前景色  
  25.         g.setColor(Color.BLACK);
  26.         g.drawString(" 没有签名图",0,25);
  27.         g.dispose();
  28.         //  
  29.         JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(outStream);
  30.         encoder.encode(image);
  31.         outStream.flush();
  32.         //outStream.close();  
  33.   }catch(Exception e){
  34.     Log.fetal("at noImg in sig2.jsp:/n"+e);
  35.   }
  36. }
  37. public void noImg(HttpServletResponse response){
  38.   try{
  39.         ServletOutputStream outStream = response.getOutputStream();
  40.         noImg(outStream);
  41.   }catch(Exception e){
  42.     Log.fetal("at noImg in sig2.jsp:/n"+e);
  43.   }
  44. }
  45. %>
  46. <%
  47.     out.clear();
  48.     response.setContentType("image/jpeg");
  49.     response.addHeader("pragma","NO-cache");
  50.     response.addHeader("Cache-Control","no-cache");
  51.     response.addDateHeader("Expries",0);
  52.     int id = StrUtil.StrToInt(request.getParameter("id"));
  53.     if(id<=0)
  54.     {
  55.         noImg(response);
  56.     }
  57.     else
  58.     {
  59.         java.sql.Connection conn = null;
  60.         java.sql.Statement stmt = null;
  61.         java.sql.ResultSet lobDetails = null;
  62.         try {
  63.             conn = DBUtil.getConn();
  64.             stmt = conn.createStatement();
  65.             lobDetails = stmt.executeQuery(
  66.                 "SELECT Signature FROM OZ_Member " +
  67.                 "WHERE MemberID = " + id + " ");
  68.             if (lobDetails.next()) {
  69.                 Blob mapBlob = lobDetails.getBlob(1);
  70.                 if(mapBlob!=null){
  71.                 InputStream blobStream = mapBlob.getBinaryStream();
  72.                 Log.debug("blobStream:"+blobStream);
  73.                 ServletOutputStream outStream = response.getOutputStream();
  74.                 byte[] buffer = new byte[10 * 1024];
  75.                 int nbytes = 0;
  76.                int allBytes = 0;
  77.                 while( (nbytes = blobStream.read(buffer)) != -1 ){
  78.                     outStream.write(buffer, 0, nbytes);
  79.                     allBytes +=nbytes;
  80.                 }
  81.                 Log.debug("allBytes:"+allBytes);
  82.                 if(allBytes<1){
  83.                   Log.debug("allBytes 2:"+allBytes);
  84.                  noImg(outStream);
  85.                 }else{
  86.                   outStream.flush();
  87.                   //outStream.close();  
  88.                 }
  89.                 blobStream.close();
  90.             }else{
  91.                 noImg(response);
  92.             }
  93.             }else{
  94.                 noImg(response);
  95.             }
  96.         }
  97.         catch (Exception e) {
  98.           Log.fetal(e);
  99.         }
  100.         finally {
  101.           try {lobDetails.close();}catch (Exception e) {}
  102.           try {stmt.close();}catch (Exception e) {}
  103.           try {conn.close();}catch (Exception e) {}
  104.         }
  105.     }
  106. %>
  107. 修改后的代码=============== by yanleigis
  108. <%@ page contentType="text/html; charset=GBK" %>
  109. <%@ page autoFlush="false" %>
  110. <%@ page import="java.sql.*" %>
  111. <%@ page import="java.io.*" %>
  112. <%@ page import="java.util.*" %>
  113. <%@ page import="java.awt.*" %>
  114. <%@ page import="java.awt.image.*" %>
  115. <%@ page import="com.sun.image.codec.jpeg.*" %>
  116. <%@ page import="com.sun.image.codec.jpeg.*" %>
  117. <%@ page import="com.csland.common.util.*" %>
  118. <%!
  119. public void noImg(ServletOutputStream outStream){
  120.   try{
  121.         int width=80, height=50;
  122.         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  123.         Graphics g = image.getGraphics();
  124.         //以下填充背景颜色  
  125.         g.setColor(Color.WHITE);
  126.         g.fillRect(00, width, height);
  127.         g.setColor(Color.ORANGE);
  128.         g.drawRect(00, width-1, height-1);
  129.         String random="random";
  130.         //以下设置前景色  
  131.         g.setColor(Color.BLACK);
  132.         g.drawString(" 没有签名图",0,25);
  133.         g.dispose();
  134.         //  
  135.         JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(outStream);
  136.         encoder.encode(image);
  137.         outStream.flush();
  138.         outStream.close();
  139.   }catch(Exception e){
  140.     Log.fetal("at noImg in sig2.jsp:/n"+e);
  141.   }
  142. }
  143. public void noImg(HttpServletResponse response){
  144.   try{
  145.         ServletOutputStream outStream = response.getOutputStream();
  146.         noImg(outStream);
  147.   }catch(Exception e){
  148.     Log.fetal("at noImg in sig2.jsp:/n"+e);
  149.   }
  150. }
  151. %>
  152. <%
  153.     out.clear();
  154.     out = pageContext.pushBody();
  155.     response.setContentType("image/jpeg");
  156.     response.addHeader("pragma","NO-cache");
  157.     response.addHeader("Cache-Control","no-cache");
  158.     response.addDateHeader("Expries",0);
  159.     int id = StrUtil.StrToInt(request.getParameter("id"));
  160.     if(id<=0)
  161.     {
  162.         noImg(response);
  163.     }
  164.     else
  165.     {
  166.         java.sql.Connection conn = null;
  167.         java.sql.Statement stmt = null;
  168.         java.sql.ResultSet lobDetails = null;
  169.         try {
  170.             conn = DBUtil.getConn();
  171.             stmt = conn.createStatement();
  172.             lobDetails = stmt.executeQuery(
  173.                 "SELECT Signature FROM OZ_Member " +
  174.                 "WHERE MemberID = " + id + " ");
  175.             if (lobDetails.next()) {
  176.                 Blob mapBlob = lobDetails.getBlob(1);
  177.                 if(mapBlob!=null){
  178.                 InputStream blobStream = mapBlob.getBinaryStream();
  179.                 Log.debug("blobStream:"+blobStream);
  180.                 ServletOutputStream outStream = response.getOutputStream();
  181.                 byte[] buffer = new byte[10 * 1024];
  182.                 int nbytes = 0;
  183.                int allBytes = 0;
  184.                 while( (nbytes = blobStream.read(buffer)) != -1 ){
  185.                     outStream.write(buffer, 0, nbytes);
  186.                     allBytes +=nbytes;
  187.                 }
  188.                 Log.debug("allBytes:"+allBytes);
  189.                 if(allBytes<1){
  190.                   Log.debug("allBytes 2:"+allBytes);
  191.                  noImg(outStream);
  192.                 }else{
  193.                   outStream.flush();
  194.                   //outStream.close();  
  195.                 }
  196.                 blobStream.close();
  197.             }else{
  198.                 noImg(response);
  199.             }
  200.             }else{
  201.                 noImg(response);
  202.             }
  203.          response.flushBuffer();   
  204.      out.clear();   
  205.      out  =  pageContext.pushBody();   
  206.         }
  207.         catch (Exception e) {
  208.           Log.fetal(e);
  209.         }
  210.         finally {
  211.           try {lobDetails.close();}catch (Exception e) {}
  212.           try {stmt.close();}catch (Exception e) {}
  213.           try {conn.close();}catch (Exception e) {}
  214.         }
  215.     }
  216. %>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值