1

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,

2 Answers 2

5

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()
   }
}
Sign up to request clarification or add additional context in comments.

3 Comments

David, I'm having some trouble with this approach, when I add some node with a literal UTF-8 string such as "áéíóú" it's encoded in ISO and delivered to the browser like that, despite the documents encoding definition and http response's encoding.. why is that?
Have you checked the encoding of the Java source file itself? Are you using an XML serialization method or constructor which defaults to the platform encoding and has an overloaded version which allows you to force UTF-8?
The file encoding was correct, I solved this here: stackoverflow.com/questions/12606462/… thanks David
2

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());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.