gpt4 book ai didi

java - 在 jsf 页面中使用命令按钮下载文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:36:23 26 4
gpt4 key购买 nike

在 jsf 页面中使用命令按钮下载文件。使用:JSF 和 Richfaces。

我有一个表(扩展了 ExtendedDataModel 实现 Modifiable、Serializable),其中包含一些数据,每行都有一个“下载”按钮。

<a4j:commandButton id="getDownload" value="download" 
style="margin-left:10px;margin-right:10px;width:100px;"
action="#{controller.download}" immediate="true" ajaxSingle="true">
<f:setPropertyActionListener target="#{controller.idString}" value="#{item.id}" />
</a4j:commandButton>

我必须在 Controller 中构建文件:

public void download(){
OutputStream out = null;
....

FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
out = response.getOutputStream();

ZipOutputStream zipout = new ZipOutputStream(out);
.....

zipout.close();
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename=\""+filename+"\"");
out.flush();
....

} finally {
try {
if (out!=null){
out.close();
}
FacesContext.getCurrentInstance().responseComplete();
} catch (IOException e) {
logger.error(e);
}

}
...
}

当我自己实现 ExtendedDataModel 时,问题就开始了。起初我使用 h:commandLink,但 Controller 方法从未被调用过……我试了又试……现在调用了正确的方法,但页面中显示了 (zip) 文件内容。我想要页面中的按钮/链接,用户可以单击它来下载文件。页面本身不应更改。有任何想法吗?

我可以创建一个 servlet,但我不明白为什么 ExtendedDataModel 会改变内部链接的行为。

编辑1

我用过

<h:commandLink id="getDownload" value="download" action="#{controller.download}">                                                       
<f:setPropertyActionListener target="#{controller.idString}" value="#{item.id}" />
</h:commandLink>

之前。它适用于“普通”richfaces 表,但当我在我自己的扩展 ExtendedDataModel 的表中使用它时则不行。

编辑 2 - 解决方案/解决方法

无法使用 h:commandButton, .. Link... 自制表格中的任何内容来下载文件。我现在使用表中的一个按钮来呈现新的 PanelGroup,并使用新 PanelGroupt 中的第二个按钮来下载文件。我为此在谷歌上搜索了很多,看起来像是一个有钱人脸的错误。

最佳答案

您不能通过 ajax 请求下载文件。替换 a4j:commandButton通过 h:commandButton .


更新 根据您的问题更新:在 UIData 中获取命令链接/按钮组件如 <h:dataTable> , <rich:dataTable>等工作,您需要确保持有数据模型的 bean(value 组件的 UIData 属性后面的任何内容)在表单提交请求期间保留完全相同的数据模型。如果您想保持 bean 请求的范围,那么最简单的方法是在 <a4j:keepAlive> 中引用 bean。标签。

关于java - 在 jsf 页面中使用命令按钮下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4335849/

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