Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create XML with JSF

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.

like image 589
Kiva Avatar asked Aug 25 '09 10:08

Kiva


2 Answers

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.

like image 173
Damo Avatar answered Sep 28 '22 02:09

Damo


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.

like image 20
Steve Claridge Avatar answered Sep 28 '22 02:09

Steve Claridge