Primefaces filedownload错误处理

时间:2011-04-07 16:50:25

标签: jsf-2 primefaces

如何使用primefaces filedownload处理错误

<p:fileDownload value="#{testBean.file}" /> 

TestBean.java

    public StreamedContent getFile() {  
    if(selectedReport ==null){
        FacesContext.getCurrentInstance().addMessage(.."Please select a file");
        return null;//What to do here
    }
    InputStream inps =  ReportGenerator.getPDF(selectedReport);
    return new DefaultStreamedContent(inps, "application/pdf", "report.pdf"); 
    }

3 个答案:

答案 0 :(得分:0)

如果你的意思是处理错误 向用户显示一条html消息,那么你应该把可能引发异常的代码放在try...catch块中,catch块将内容类型更改回text/html并以您希望的方式显示错误。

但由于内容类型已添加到DefaultStreamedContent中,因此可能只有重定向才能解决此问题。

答案 1 :(得分:0)

这有助于http://forum.primefaces.org/viewtopic.php?f=3&t=8263

<p:commandButton    ajax="false"
                    value="Download Detailed Report"
                    actionListener="#{reportBean.generateDetailedReport}">

    <p:fileDownload value="#{reportBean.detailedReport}"/>

</p:commandButton>
public void generateDetailedReport(ActionEvent ae) {

    ......

    reportStream = ExcelReport.generate(reportList);

    if (reportStream == null) {

        FacesUtil.addError("Error generating report");

        throw new AbortProcessingException();
    }
}

public StreamedContent getDetailedReport() {

    return new DefaultStreamedContent(reportStream, "application/xls", "report.xls"); 
}

答案 2 :(得分:0)

最好使用获取所有异常之类的;

} catch (Exception e) {
        handleError(e);
    }

handleError方法;

private void handleError (Throwable t) {

    try {
        throw t;
    } catch (AccessException ae) {
        FacesUtil.setErrorMessage("CCCCCCC");           
    } catch (SQLException sqle) {
        FacesUtil.setErrorMessage("CCCCCCC");           
    } catch (ConnectException ce) {
        FacesUtil.setErrorMessage("CCCCCCC");           
    } catch (RemoteException re) {
        FacesUtil.setErrorMessage("CCCCCCC");           
    } catch (NotBoundException nbe) {
        FacesUtil.setErrorMessage("CCCCCCC");           
    } catch (IOException ioe) {
        FacesUtil.setErrorMessage("CCCCCCC");           
    } catch (IllegalArgumentException iae) {
        FacesUtil.setErrorMessage("CCCCCCC");           
    } catch (Throwable tt) {
        FacesUtil.setErrorMessage("CCCCCCC");           
    }

    FacesUtil.completeResponse();
}