In Play, the response to a request is a result. A result has two components: the response header and the response body. Let's look at a simple example of this:
def plainResult = Action { Result( header = ResponseHeader(200, Map(CONTENT_TYPE -> "text/plain")), body = Enumerator("This is the response from plainResult method".getBytes()) ) }
Notice that we used an enumerator for the response body. An enumerator is a means to provide data to an iteratee. We will discuss these in detail in Chapter 6, Reactive Data Streams.
Apart from this, a result has additional functions that equips us with better means to handle response headers, sessions, cookies, and so on.
A result can send JSON, XML, and images as a response, apart from a String content. An easier way of generating a result is to use the result helpers. A result helper is used for most of the HTTP response status. As an example, let's see how the TODO
Action that comes built in with Play is implemented:
val TODO = Action { NotImplemented[play.api.templates.Html](views.html.defaultpages.todo()) }
In this snippet, NotImplemented
is a helper, which returns a result with a status of 501 and views.html.defaultpages.todo()
returns the default page, which is todo.scala.html
.
As an example, we'll consider the Action that sends the user's profile image inline. The Action would now be as follows:
def getUserImage(userId: Long) = Action { val path: String = s"/socialize/user/$userId.jpeg" val img = new File(path) if (img.exists()) { Ok.sendFile( content = img, inline = true ) } else NoContent }
Here, we attempt to load the user's profile image using the predefined getUserImagePath
method. If the image file exists and attaches itself to the response, we return a response with the 204
status code.
We also saw how a result helper can be used to send the page content, both static and dynamic, using views:
def listArtist = Action { Ok(views.html.home(Artist.fetch)) }
We could also use the Status
class to generate the result, as shown here:
def save = Action(parse.text) { request => Status(200)("Got: " + request.body) }
This table shows you the result helpers and their corresponding status codes:
3.144.30.178