在文件下载方法

时间:2016-07-26 11:33:03

标签: primefaces jsf-2.2

我有一个JSF 2.2 xhtml页面,表格标签内有一个按钮,如下所示 - 可以下载文件。

<h:form>
   <p:commandButton onclick="PrimeFaces.monitorDownload(start, stop);"
       value="#{filename}"
       id="download">
       <p:fileDownload 
       value = "#{downloadController.downloader(downloadController.file,
       reviewTableController.exam.id, filename)}" />
   </p:commandButton>
   <h:message for="download"/>
</h:form>

DownloadController(相关部分):

@Named
@ViewScoped
public class DownloadController implements Serializable {
    // other stuff    
    public StreamedContent downloader(StreamedContent file, int id, String filename) { 
    String resourcef = "/resources/default/files/"+filename;
    InputStream stream = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream(resourcef);
    file = new DefaultStreamedContent(stream, "application/pdf", filename);
    return file;
}

public StreamedContent getFile() throws IOException  {
    if (file == null) {
        System.out.println("File has not been placed in resources");
    } 
    if (file != null) {
            file.getStream().reset();   
    }
    return file;
} 
// getters and setters ...
}

因此,如果正确命名的文件已放置在正确的位置,则用户可以下载文件。但是,可能存在具有给定文件名的文件在应从中下载的位置。

目前在这种情况下我收到错误(500):

[2016-07-26T08:29:44.078+1000] [glassfish 4.1] [WARNING] [] 
[javax.enterprise.web] [tid: _ThreadID=108 _ThreadName = http-listener-1(1)]    
[timeMillis: 1469485784078] [levelValue: 900] [[
StandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception
java.lang.NullPointerException
at org.primefaces.component.filedownload.FileDownloadActionListener.processAction(FileDownloadActionListener.java:77)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at com.sun.faces.facelets.component.UIRepeat.broadcast(UIRepeat.java:1045)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
// etc

显然发生错误是因为getFile()仍然必须返回一个文件,即使它是空的

而不是那样,我想在xhtml页面上发生一条消息。它不必是一个FacesMessage,一个简单的h:消息或p:消息,例如&#34;文件没有放在资源中#34;会做的。

我无法弄清楚如何将DownloadController中的异常事件连接到xhtml页面中的h:消息。 或者更确切地说,如果有办法避免例外;仍在注册或注意该文件为空,并且在这种情况下提供h:消息 - 或者如果文件存在则返回该文件。

任何帮助或评论表示赞赏。感谢

0 个答案:

没有答案