当前位置: 首页 > 知识库问答 >
问题:

java.lang.IllegalStateException:已经为此响应调用了getOutputStream()

慕容念
2023-03-14
HTTP Status 500 - Unable to show problem report: java.lang.IllegalStateException: getOutputStream() has already been called for this response

代码:

WorkbookSettings wbSettings = new WorkbookSettings();    
OutputStream outStream = null;
            
try
{               
  wbSettings.setLocale(new Locale("en", "EN"));             
  response.setContentType("application/vnd.ms-excel");                  
  outStream= response.getOutputStream();                
  response.setHeader("Content-Disposition", "attachment; filename=/timesheet.xls");             
  WritableWorkbook workbook = Workbook.createWorkbook(outStream, wbSettings);              
  workbook.createSheet("Report", 0);               
  WritableSheet excelSheet = workbook.getSheet(0);              
  service.createLabel(excelSheet);              
  service.createContent(excelSheet);                    
  workbook.write();             
  workbook.close();             
  outStream.flush();               
  outStream.close();                
}               
catch(Exception e)
{
}           
finally
{               
  //outStream.close();      
}   
return "generateReport";

我的struts.xml如下所示:

<result type="stream" name="generateReport">                   
 <param name="contentType">"application/vnd.ms-excel"</param>                  
 <param name="inputName">excelstream</param>                  
 <param name="contentDisposition">contentDisposition</param>                   
 <param name="bufferSize">1024</param>              
</result>

在JSP中,我只是给出了一个按钮,它给出了打开,保存对话框。单击该按钮后,我将获得异常。

如何避免这一点?

共有1个答案

祁俊拔
2023-03-14

这只是一个语法错误,服务器在困惑如何处理这样的内容类型

<param name="contentType">"application/vnd.ms-excel"</param>

更改为

<param name="contentType">application/vnd.ms-excel</param>

注意,param值是一个没有双引号的字符串。

<result type="stream" name="generateReport">
  <param name="contentType">application/vnd.ms-excel</param>
  <param name="contentDisposition">attachment;filename="timesheet.xls"</param>
  <param name="inputName">excelstream</param>
</result>
private InputStream excelstream;

public InputStream getExcelstream() {
  return excelstream;
}  

public String execute() throws Exception {
  WorkbookSettings wbSettings = new WorkbookSettings();

  try  {  
    ByteArrayOutputStream outstream = new ByteArrayOutputStream();  
    wbSettings.setLocale(new Locale("en", "EN"));        
    WritableWorkbook workbook = Workbook.createWorkbook(outstream, wbSettings);   
    workbook.createSheet("Report", 0);    
    WritableSheet excelSheet = workbook.getSheet(0);    
    service.createLabel(excelSheet);    
    service.createContent(excelSheet);          
    workbook.write();    
    workbook.close();  
    excelstream = new ByteArrayInputStream(outstream.toByteArray());        
  } catch(Exception e) {    
    e.printStackTrace();
    throw e;
  }

  return "generateReport";
}
 类似资料: