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>");
}
XML request and response support consists of two main functions: The XML parsing function parses an inbound XML request message and maps XML elements to a fixed format COMMAREA. See XML message formats for a sample of a request message in XML format.
Changing the default Content-Type Will automatically set the Content-Type header to text/plain , while: JsonNode json = Json. toJson(object); Result jsonResult = ok(json); will set the Content-Type header to application/json .
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With