struts2文件图片流输出报IllegalStateException: Cannot call sendError() after the response has been committed

本文介绍了一个Struts2框架中使用图片流时遇到的java.lang.IllegalStateException异常问题及解决方案。通过调整代码返回值从SUCCESS到null解决了异常,并强调了流操作中的注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

struts2图片后端以流的形式传给前端并显示时,控制台报java.lang.IllegalStateException: Cannot call sendError() after the response has been committed异常.
文件可以正常下载,只是后台报异常.
未修改前代码如下:

 try{
              VO vo = new VO();
              String filepath = Param.getValue("LOCALACTIVITY", "FILEPATH")+id+postfix;
              System.out.println("filepath"+filepath);
              File file = new File(filepath);
              DataOutputStream temps = new DataOutputStream(response.getOutputStream());;
              DataInputStream in = null;
              response.setContentType("image/*");
              if (file.exists() ) {
                  in = new DataInputStream(new FileInputStream(file));
                    int len=0;
                    byte[] b = new byte[2048];
                    while ((len=in.read(b)) != -1) {
                        temps.write(b,0,len);
                        temps.flush();
                    }
                    in.close();
                    temps.close();
              }
              else{
                    file = new File(Param.getValue("LOCALACTIVITY", "FILEPATH")+"\\default\\default.png");                  
                    in = new DataInputStream(new FileInputStream(file));    
                    int len=0;
                    byte[] b = new byte[2048];
                    while ((len=in.read(b)) != -1) {
                        temps.write(b,0,len);
                        temps.flush();
                    }
                    in.close();
                    temps.close();
              }
          } 
          catch (Exception e) {
            log.debug("===========查询图片时报错"+e);
        }
          log.debug("===========查询图片结束");
          return SUCCESS;

研究发现可能是struts2本身的bug,将return SUCCESS 改为return null,即可解决问题.
需要注意的地方:
1.在各分支内部关闭输出流,不要统一关闭.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值