Reputation: 25
In the JSF page I have:
<p:commandButton value="Download" action="#{myMBean.downloadXMLFile}" />
In the MBean I have the following (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();
}
But when I run it, I get an IllegalStateException:
java.lang.IllegalStateException: setBufferSize() called after first write to Output Stream/Writer
I tried also to convert the XML String to a Document and converting it to a File but got the same error. is it really necessary in order to work?
Upvotes: 1
Views: 1920
Reputation: 23637
The error occurs because of an attempt to render your response during the JSF render phase.
You are using a raw response object obtained via ExternalContext
, and writing the response yourself. You must tell the JSF runtime that the response is complete so it doesn't attempt to process it.
Save a reference to your FacesContext
:
FacesContext ctx = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
...
and call responseComplete()
when you finish building your response:
ctx.responseComplete();
Upvotes: 2