在JSF页面中我有:
<p:commandButton value="Download" action="#{myMBean.downloadXMLFile}" />
在MBean中,我有以下内容(try/catch已提交):
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字符串转换为文档并将其转换为文件,但得到了相同的错误。为了工作真的有必要吗?
由于在JSF呈现阶段尝试呈现响应而发生错误。
您正在使用通过ExternalContext
获得的原始响应对象,并自己编写响应。您必须告诉JSF运行时响应已经完成,这样它就不会尝试处理它。
保存引用到您的FacesContext
:
FacesContext ctx = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
...
和调用responseComplete()
当你完成构建你的响应:
ctx.responseComplete();