动作链接和下载链接于一体

Her*_*zog 1 download jsf-2

我需要在JSF 2应用程序的页面上显示一个下载文件的链接.现在,问题是该文件包含的数据取决于创建时对数据库的全新外观.但我想要做的是创建它并给用户一个链接,以便在一个动作中下载它.

这在两个操作中非常简单:使用按钮生成文件,并将其替换为生成文件后下载文件的链接.

那么问题是,这可以通过一次单击commandLink来完成吗?

编辑,遵循BalusC的评论如下.这是我要做的事情的具体细节,到目前为止已经完成了.我在xhtml中有这个:

<h:panelGroup rendered="#{!bean.showLinkToExcelFile()}">
     <h:form>
         <td><h:commandButton value="Generate list of your Bids for download" action="#{bean.createBidsList()}"/></td>      
    </h:form>
</h:panelGroup>
<h:panelGroup rendered="#{bean.showLinkToExcelFile()}">
    <td><a href="#{bean.findBidsListFileName()}">Download Your Bids</a></td>
</h:panelGroup> 
Run Code Online (Sandbox Code Playgroud)

这有效.该按钮创建一个excel文件,将其保存到某个位置,并更新数据库中的文件名.然后链接提供文件.但这对用户来说是一个两步过程.我希望它只是一步.所以一个链接,例如:

<a href="#{bean.findBidsListFileName()}">Download Your Bids</a>
Run Code Online (Sandbox Code Playgroud)

或者,最有可能的是,jsf commandLink将在后端创建excel文件,将其保存到/ resources/location,并在用户的计算机上无缝打开"保存"对话框.

Bal*_*usC 5

您可以让JSF立即将报告写入OutputStreamHTTP响应而不是OutputStream本地磁盘文件系统.

这是一个基本示例,假设您使用Apache POI创建Excel报告:

public void createAndDownloadBidsReport() throws IOException {
    // Prepare Excel report to be downloaded.
    HSSFWorkbook bidsReport = createBidsReportSomehow();
    String filename = "bids.xls";

    // Prepare response to show a Save As dialogue with Excel report.
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    externalContext.setResponseContentType("application/vnd.ms-excel");
    externalContext.setResponseHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

    // Write Excel report to response body.
    bidsReport.write(externalContext.getResponseOutputStream());

    // Inform JSF that response is completed and it thus doesn't have to navigate.
    facesContext.responseComplete();
}
Run Code Online (Sandbox Code Playgroud)

这样,您最终只需要一个命令链接(或按钮).

<h:form>
    <h:commandLink value="Create and download bids report" action="#{bean.createAndDownloadBidsReport}" />
</h:form>
Run Code Online (Sandbox Code Playgroud)

请注意,这不会将其保存到磁盘文件系统.如果您确实需要一个副本,那么您需要添加另一bidsReport.write()行写入所需的磁盘文件系统位置.