在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但得到了同样的错误。为了工作真的有必要吗?
答案 0 :(得分:2)
由于尝试在JSF呈现阶段呈现响应而发生错误。
您正在使用通过ExternalContext
获得的原始响应对象,并自行编写响应。您必须告诉JSF运行时响应已完成,因此它不会尝试处理它。
保存对FacesContext
:
FacesContext ctx = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
...
并在完成构建答案后致电responseComplete()
:
ctx.responseComplete();