5
votes

Somehow I can't figure out how to get Play! to serve an XML response. And I don't understand the documentation either (which you can find here).

My goal is to create a sitemap, so the response should be a Content-Type: application/xml;

How would you alter the following controller to serve that Content-Type?

public static Result sitemap() {
    return ok("<message \"status\"=\"OK\">Hello Paul</message>");
}
1
Have you tried adding the @BodyParser.Of(Xml.class) annotation to your sitemap-method? - tehlexx
Yes, it still serves a "text/plain" :/ - Crayl
There are different ways... as tehlexx mentioned by using the @BodyParser Annotation (set correct mime type with response().setContentType("application/xml")) or even simpler: Use templates,like you do with HTML Pages. Thats probably the fastest method to generate some XML response. - Jürgen Zornig
Wow, awesome. This works. Thanks! But the @BodyParser Annotations isn't necessary, response().setContentType("application/xml") does the job. Thank you very much. Why don't you put your comment as an answer? So I can mark it as correct. - Crayl

1 Answers

13
votes

Play will set Content-type header properly if you will deliver it to ok() method in right way. For an example if you are returning the String (as you showed in question) it considers that's text/plain. You have at least 2 ways, the fastest (but ugly) is forcing content type, Jürgen suggest setting it to response, but de facto Play has a shortcut:

public static Result sitemap() {
    return ok("<message status=\"OK\">Hello Paul</message>").as("text/xml");
}

On the other hand probably using XML template is better and cleaner option than building it with glued strings... Just create the XML file:

/app/views/sitemap.scala.xml:

<message status="OK">John Doe</message>

So you can use it as easy as:

public static Result index() {
    return ok(views.xml.sitemap.render());
}

Of course this file is common Play's template, so you can pass data to it and process inside (ie. iterate list of items, etc)