在同一页面上处理丢失的文件下载链接而无需请求

时间:2012-10-31 14:41:19

标签: java jsf java-ee jsf-2

当缺少相应的文件时,处理文件下载链接点击的最佳做法是什么?

具体情况是数据库中存在附件实体,仅指向文件名,文件存储路径可以单独/单独配置。这适用于遗留应用,必须得到支持。

这可能吗?这样的代码怎么样?我试过了

    if ( file.canRead() )
    {
        byte[] data = FileUtils.readFileToByteArray( file );

        // goes to code like here: http://balusc.blogspot.de/2006/05/pdf-handling.html
        downloadFile( attachment.getFileName(), data );
    }
    else
    {
        this.log.errorv( "Attachment {0} not found in configured storage path {1}", file, this.storagePath );

        FacesContext facesContext = FacesContext.getCurrentInstance();

        facesContext.addMessage( null,
                                 new FacesMessage( FacesMessage.SEVERITY_ERROR, "Failed.",
                                                   "Downlosding file " + file + " failed! File doesn't exist in the configured storage path " + this.storagePath ) );

        // ???
        facesContext.responseComplete();
    }

但这会导致

XML-Verarbeitungsfehler: Kein Element gefunden
Adresse: https://localhost:8181/cmc-compliance/view/prototype/collisionManager.xhtml
Zeile Nr. 1, Spalte 1:

<rant> OMG,我 HATE ...呃 DISLIKE int18ned错误消息......有人应该摆脱认为这是个好主意的人...... </rant>

好的,上面的意思是“XML处理错误:找不到元素+第1行,第1列”

我的代码显然不是正确的方法......

我在数据表中使用JSF代码:

<h:commandLink action="#{attachmentManager.downloadAttachment(att)}">
    <h:graphicImage library="images/icons" name="page_white.png" />
    <h:outputText value="#{att.fileName}" />
</h:commandLink>

我理想的是显示JSF消息(或PrimeFaces咆哮)然后保持原样,即不再在同一页面上发出完整请求。

你是怎么做到的?

1 个答案:

答案 0 :(得分:2)

使用facesContext.responseComplete();,您基本上阻止了JSF呈现响应。因此,客户端检索完全空的响应。 webbrowser正在努力发挥其作用。所有webbrowser都知道所请求的资源具有.xhtml文件扩展名。因此,webbrowser假设它是一些XML内容。然后webbrowser尝试将空响应解析为XML。但由于没有任何XML元素,它在给定错误时失败了。 XML格式良好的文档要求至少一个根XML元素。

删除facesContext.responseComplete();行,然后按常规方式从方法返回。当已经已经自行写入时,


  

OMG,我讨厌错误消息......有人应该摆脱认为这是个好主意的人......

只需在平台特定设置中相应地更改操作系统平台默认语言环境。对于Windows,可以在此处找到带有屏幕截图的相关答案:Getting OS language in java。如果程序本身(例如Firefox / Chrome)也有一些与语言环境相关的设置,您可能也想在程序本身中更改它。