getOutputStream()使用可编程下载导致java.lang.IllegalStateException

时间:2016-10-07 10:54:11

标签: java jsf-2 error-handling tomcat6

使用可编程下载,生成文件在进程中可能非常耗时(相对),并且使用Web应用程序,用户可以调用不同的URL,从而突然放弃整个操作。

当潜在页面加载时,我点击了一个不同的URL,然后我得到了:

getOutputStream has already been called for this response exception

代码的摘录:

/*
 * File generation appears above the following code.
 */
String contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();


ec.responseReset();
ec.setResponseContentType(contentType);
ec.setResponseContentLength((int) f.length());
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + nomFichier + "\"");

OutputStream output = null;
InputStream input = null;
try {
    output = ec.getResponseOutputStream();
    input = new FileInputStream(f);
    byte[] buffer = new byte[1024];
    int i;
    while ((i=input.read(buffer)) != -1) {  
        output.write(buffer,0,i);  
        output.flush();  
    }               
    fc.responseComplete();
    fc.renderResponse();

} catch (IOException e) {
    logger.log(Level.ERROR, e);
} finally {
    try {
        if (input != null) {
                input.close();
        }
        if (output != null) {
            output.flush();
        }

    } catch (IOException e) {
        logger.log(Level.INFO, e);
        String message = e.getMessage();
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
    }
    if(f.delete()){
        logger.log(Level.INFO, "Fichier " + f.getName() + " Supprimé");
    }else{
        logger.log(Level.INFO, "Fichier " + f.getName() + " n'A pas Etre Supprimé");
    }
}

无论如何,错误是非阻塞的,我只是想处理它。

我应该使用同步关键字吗?

0 个答案:

没有答案