如何在JSF中下载XML动态生成的文件?

时间:2014-05-12 18:00:13

标签: java xml jsf download

在JSF页面中我有:

<p:commandButton value="Download" action="#{myMBean.downloadXMLFile}" />

在MBean中,我有以下内容(try / catch ommited):

public void downloadXMLFile() {

String xml = this.getXML();//returns the whole XML but in String format.
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();  
response.setContentType("text/xml");
response.setHeader("Content-Disposition", "attachment;filename=file.xml");  

ServletOutputStream out = response.getOutputStream();
out.write(xml.getBytes());  
out.flush(); 
}

但是当我运行它时,我得到一个IllegalStateException:

java.lang.IllegalStateException: setBufferSize() called after first write to Output Stream/Writer

我还尝试将XML String转换为Document并将其转换为File但得到了同样的错误。为了工作真的有必要吗?

1 个答案:

答案 0 :(得分:2)

由于尝试在JSF呈现阶段呈现响应而发生错误。

您正在使用通过ExternalContext获得的原始响应对象,并自行编写响应。您必须告诉JSF运行时响应已完成,因此它不会尝试处理它。

保存对FacesContext

的引用
FacesContext ctx = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
...

并在完成构建答案后致电responseComplete()

ctx.responseComplete();