Using View templates, we are also able to respond to HTTP requests in other content types such as text files and XML data formats. Play Framework has native handlers for XML and text file content type responses.
For Java, we need to take the following steps:
Run the
foo_java
application with Hot-Reloading enabled:$ activator "~run"
Create the text-based view template file
products.scala.txt
inapp/views/
and add the following content:@(productMap: Map[Integer, String]) @for((id, name) <- productMap) { The Product '@name' has an ID of @id }
Create the XML-based view template file
products.scala.xml
inapp/views/
and add the following content:@(productMap: Map[Integer, String]) <products> @for((id, name) <- productMap) { <product id="@id">@name</product> } </products>
Edit
foo_java/app/controllers/Application.java
by adding the following actions:public static Result listProductsAsXML() { return ok(views.xml.products.render(productMap)); } public static Result listProductsAsTXT() { return ok(views.txt.products.render(productMap)); }
Edit
foo_java/conf/routes
by adding the following lines:GET /products.txt controllers.Application.listProductsAsTXT() GET /products.xml controllers.Application.listProductsAsXML()
View the new routes and actions using a web browser:
http://localhost:9000/products.txt
and,http://localhost:9000/products.xml
For Scala, we need to take the following steps:
Run the
foo_scala
application with Hot-Reloading enabled:$ activator "~run"
Create the text-based view template file
products.scala.txt
inapp/views/
and add the following content:@(productMap: Map[Int, String]) @for((id, name) <- productMap) { The Product '@name' has an ID of @id }
Create the XML-based view template file
products.scala.xml
inapp/views/
and add the following content:@(productMap: Map[Int, String]) <products> @for((id, name) <- productMap) { <product id="@id">@name</product> } </products>
Edit
foo_scala/app/controllers/Application.scala
by adding the following actions:def listProductsAsTXT = Action { Ok(views.txt.products(productMap)) } def listProductsAsXML = Action { Ok(views.xml.products(productMap)) }
Edit
foo_scala/conf/routes
by adding the following lines:GET /products.txt controllers.Application.listProductsAsTXT GET /products.xml controllers.Application.listProductsAsXML
View the new routes and actions using a web browser:
http://localhost:9000/products.txt
andhttp://localhost:9000/products.xml
In this recipe, we utilized build-in support for other content types in Play Framework. We created new URL routes and web actions to be able to respond to requests for data in XML or text file formats. By following file naming standards and convention for views, we were able to create view templates in HTML, XML, and text file formats, which Play automatically handles, and then adds the appropriate content type headers in the HTTP response.