我的异常java.lang.IllegalStateException

java.lang.IllegalStateException: getCompressingOutputStream() has already been called

public void downloadTemplate(HttpServletRequest request,HttpServletResponse response,String templatePath,String title) {
        InputStream in=null;
        try {
            in = request.getServletContext().getResourceAsStream("/WEB-INF/xls/"+templatePath );
            //判断读取文件失败,抛出异常
            if(in==null){
                throw new RuntimeException();
            }
            BufferedInputStream bin = new BufferedInputStream(in);
            OutputStream out = response.getOutputStream();
              byte[] buff =new byte[2048];
              int len=-1;
              do{
                  len =  bin.read(buff);
                  out.write(buff);
              }while(len>-1);
              response.setContentType("application/vnd.ms-excel");  
              response.setHeader("Content-disposition", "attachment;filename=" + new String( title.getBytes("gb2312"), "ISO8859-1" ) + ".xls");
        } catch (Exception e) {
            response.reset();
            response.setContentType("text/html;charset=gb2312");
            PrintWriter out = null;
            String url = request.getContextPath() + "/login.jhtml";
            try {
                out = response.getWriter();
                StringBuffer buffer = new StringBuffer();
                buffer.append("<script language='javascript' type='text/javascript'>");
                buffer.append("alert('模版不存在,请重试!');window.top.location.href='" + url + "'");
                buffer.append("</script>");
                out.println(buffer.toString());
                out.flush();
            } catch (IOException ee) {
            }finally{
                if(out!=null){
                    out.close();
                }
            }
        }finally{
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
    }

导致异常原因:Servlet规范说明,不能既调用 response.getOutputStream(),又调用response.getWriter(),无论先调用哪一个,在调用第二个时候应会抛出 IllegalStateException。

解决方法:
代码加入以下判断,避免同时调用response.getOutputStream(),response.getWriter()

        //判断读取文件失败,抛出异常
        if(in==null){
                throw new RuntimeException();
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值