Java Reference
In-Depth Information
doc = parser.newDocument();
System.out.println("Products=" + pc);
m.marshal(pc, doc);
System.out.println("Marshalled catalog to XML.");
} catch (JAXBException je) {
throw new ServletException(je);
} catch (ParserConfigurationException pce) {
throw new ServletException(pce);
}
source = new DOMSource(doc);
System.out.println("Returning XML source.");
return source;
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
The asXml method here hides the JAXB business of marshaling the catalog populated with
products into XML. Here's how you do it. First, create a JAXBContext on the ProductCata-
log class because that's your root element. Then create a new DOM document node and pass
in both the populated catalog object and the empty DOM node to the marshaler. JAXB will
then create the product catalog instance as XML for you, and put its result into the DOM
document. You can create the DOM document as a DOMSource using that constructor. The
DOMSource acts as a holder for a transformation source in the form of a tree. Because it im-
plements the Source interface, you can use it to pass to the transformer. There is no XML
transformation actually happening at this point because it's already done; you're just using the
transformer to write to the output stream.
So once you have your product catalog as XML, the only work left to do is to put it together
as a response within the body of the doGet method. You get the output stream from the Ht-
tpServletResponse object so that you can write your response out to it. Then set the re-
sponse MIME type as text/xml . Next wrap the response object in a StreamResult and then
use a Transformer instance to send your source object to the response stream.
Search WWH ::




Custom Search