I need to send XML to the browser with my JSF application. This XML is generated by the application. I try to create it but my JSF application sends HTML every time.
How can I change the content-type to send xml ?
Thanks for your help.
There are several ways to do this. Doing it in JSP is a bit nasty.
As already mentioned you can use a Servlet and inject/load your variables in there. Eg by accessing the session context:
MyBean myBean = (MyBean)FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("myBean");
Or you can output it to the HTTP Response from a method in your Backing Bean. Eg:
try {
String xml = "<person>damian</person>";
FacesContext ctx = FacesContext.getCurrentInstance();
final HttpServletResponse resp = (HttpServletResponse)ctx.getExternalContext().getResponse();
resp.setContentType("text/xml");
resp.setContentLength(xml.length());
resp.getOutputStream().write(xml.getBytes());
resp.getOutputStream().flush();
resp.getOutputStream().close();
ctx.responseComplete();
} catch (IOException e) {
e.printStackTrace();
}
Or if you are using Facelets you can set the response type in the <f:view>
tag.
You can set the content-type within your JSP. I assume you are using a JSP and creating the xml content from a backing bean? A JSP like this would output XML:
<%@page contentType="text/xml"%><?xml version="1.0" encoding="UTF-8"?>
<portfolio>
<stock>
<symbol>SUNW</symbol>
<name>Sun Microsystems</name>
<price>17.1</price>
</stock>
<stock>
<symbol>AOL</symbol>
<name>America Online</name>
<price>51.05</price>
</stock>
<stock>
<symbol>IBM</symbol>
<name>International Business
Machines</name>
<price>116.10</price>
</stock>
<stock>
<symbol>MOT</symbol>
<name>MOTOROLA</name>
<price>15.20</price>
</stock>
</portfolio>
You could then easily change these hardcoded values to be bean values from your backing-bean in the way you would normally do for HTML-outputting JSPs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With