gpt4 book ai didi

java - h :commandButton multiple actions: download file and render ajax table

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:18:02 24 4
gpt4 key购买 nike

我目前有 2 个命令按钮和 1 个列表框。基于列表框选择,生成的结果可以显示在可下载的文件中或呈现为 HTML 表格。 getFile() 代码基于 BalusC's PDF Handling tutorial ,而 getTable() 设置 resultTable

<h:form>
<fieldset>
<h:selectManyListbox id="listbox" value="#{form.items}">
<f:selectItems value="#{form.allItems}">
</h:selectManyListbox>
</fieldset>
<h:commandButton value="Get File" action="#{form.getFile}">
<h:commandButton value="Get Table" action="#{form.getTable}">
<f:ajax render="result_table" execute="listbox" />
</h:commandButton>
<h:panelGrid id="result_table">
<table>
<thead></thead>
<tbody>
<ui:repeat var="table" value="#{form.resultTable}">
</ui:repeat>
</tbody>
</table>
</h:panelGrid>

到目前为止,两个按钮都工作正常。但是,我想将这两个操作合并到一个按钮中。当我使用触发这两个操作的按钮对此进行测试时,没有任何反应(没有文件保存为对话框或呈现的表格)。这是因为一个 Action 是 ajax 还是因为另一个 Action 以 facesContext.responseComplete(); 结束?

<h:commandButton value="Get Both" action="#{form.getBoth}">
<f:ajax render="result_table" execute="listbox" />
</h:commandButton>

getBoth() {
getTable();
getFile();
}

另外我想要一个复选框,如果它被选中,另存为弹出对话框并呈现表格。如果未选中,则仅呈现表格。

最佳答案

不幸的是,这在 HTTP 中是不可能的。每个请求只能发回一个响应。您不能将包含 PDF 文件的响应和 ajax 响应合并为一个响应。由于这是 HTTP 限制,因此 JSF 不能为您做太多事情。此外,由于安全限制,JavaScript 无法强制浏览器弹出另存为对话框,也无法访问本地磁盘文件系统,因此根本无法使用 Ajax 下载文件。

解决方法是在单击单个按钮时触发两个 HTTP 请求,其中第二个请求返回 Content-Disposition: attachment,以便另一个请求的响应保持不变原封不动。您可以通过向命令按钮添加 onclick 来实现此目的。

<h:commandButton onclick="window.location='/context/pdfservlet/filename.pdf'">

并创建一个大致类似于this FileServlet example的PDF servlet .如您所见,不可能由此调用 JSF 操作。您必须将 PDF 下载方法重构为 HttpServlet 类,该类在 doGet() 方法中完成工作。对于 JSF 托管 bean 和 servlet 之间的任何必要通信,您可以使用 session 范围或通过请求路径或参数传递所需信息(只是 PDF 文件标识符?)。

关于java - h :commandButton multiple actions: download file and render ajax table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4304132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com