Joaquín L. Robles
Joaquín L. Robles

Reputation: 6494

XML view with Spring MVC

this is a really newbie question: How can I output XML with Spring MVC, version 3.0.3.RELEASE? I'm currently using Tiles2 with JSTL, and when I want to output PDF, i.e., I just create a view renderer that extends AbstractPdfView as follows:

public class PDFOutput extends AbstractPdfView {

    @Override
    protected void buildPdfDocument(Map<String, Object> model, Document doc,
    PdfWriter pdfWriter, HttpServletRequest request, HttpServletResponse response)
    throws Exception {

In that case, what AbstractView class should I extend to create an XML document?

Thanks in advance,

Upvotes: 1

Views: 4952

Answers (2)

Joaqu&#237;n L. Robles
Joaqu&#237;n L. Robles

Reputation: 6494

Thanks to David North, using dom4j the resulting code is the following:

public class XMLView extends AbstractView {

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

    // set headers
    response.setContentType("application/xml");
    response.setCharacterEncoding("UTF-8");

    // construct XML document

    // output XML as String
    response.getOutputStream().print(doc.asXML());
}

Upvotes: 2

David North
David North

Reputation: 1139

It's probably simplest to extend AbstractView itself. We do something like this:

public class XMLView extends AbstractView {

  private final Document _xml;

  public XMLView(final Document xml) {
    _xml = xml;
  }

  @Override
  protected void renderMergedOutputModel(final Map<String, Object> model, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    response.setContentType("application/xml");
    response.setCharacterEncoding("UTF-8");
    // do stuff to serialize _xml to response.getOutputStream()
   }
}

Upvotes: 5

Related Questions