在jsf页面中使用commandButton下载文件.使用:JSF和Richfaces.
我有一个表(扩展ExtendedDataModel实现可修改,可序列化)与一些数据,并在每一行按钮"下载".
<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>
Run Code Online (Sandbox Code Playgroud)
我必须在控制器中构建文件:
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);
}
}
...
}
Run Code Online (Sandbox Code Playgroud)
当我实现ExtendedDataModel时,问题就开始了.起初我使用了h:commandLink,但是控制器方法从未被调用过...我试过......现在调用了正确的方法,但是(zip)文件内容显示在页面中.我想在页面中有一个按钮/链接,用户可以单击该链接下载文件.页面本身不应该改变.有任何想法吗?
我可以创建一个servlet,但我不明白为什么ExtendedDataModel改变了里面链接的行为.
EDIT1
我用了
<h:commandLink id="getDownload" value="download" action="#{controller.download}">
<f:setPropertyActionListener target="#{controller.idString}" value="#{item.id}" /> …Run Code Online (Sandbox Code Playgroud)