在jsf页面中使用commandButton下载文件
在jsf页面中使用commandButton下载文件。 使用:JSF和Richfaces。
我有一个表(扩展ExtendedDataModel实现可修改,可序列化)与一些数据,并在每一行按钮“下载”。
我必须在控制器中构建文件:
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,但是控制器方法从未被调用过……我试过了…现在调用了正确的方法,但是(zip)文件内容显示在页面中。 我想在页面中有一个按钮/链接,用户可以单击该链接下载文件。 页面本身不应该改变。 有任何想法吗?
我可以创建一个servlet,但我不明白为什么ExtendedDataModel改变了里面链接的行为。
EDIT1
我用了
之前。 它适用于“普通”richfaces表,但不是当我在我自己的表中使用它扩展ExtendedDataModel时。
编辑2 – 解决方案/解决方法
不可能使用h:commandButton,.. Link …在自制表的内部,下载文件。 我现在使用表中的一个按钮来渲染新的PanelGroup,并在新的PanelGroupt中使用第二个按钮来下载文件。 我为此搜索了很多,似乎是一个富有面孔的bug。
您无法通过ajax请求下载文件。 用h:commandButton
替换a4j:commandButton
h:commandButton
。
根据您的问题更新更新:要获取UIData
组件(如
,
等)中的命令链接/按钮才能工作,您需要确保持有数据模型的bean(无论如何)在UIData
组件的value
属性后面是在表单提交请求期间保留完全相同的数据模型。 如果要保持bean请求作用域,那么最简单的方法是在
标记中引用bean。
public class Controller { OutputStream out = null; String filename = "ali.pdf"; public void download() throws IOException { FacesContext fc = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse(); out = response.getOutputStream(); ZipOutputStream zipout = new ZipOutputStream(out); response.setContentType("application/octet-stream"); response.addHeader("Content-Disposition", "attachment; filename=\""+filename+"\""); out.flush(); try { if (out != null) { out.close(); } FacesContext.getCurrentInstance().responseComplete(); } catch (IOException e) { } }