Exploring the results

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:

Result helper

Status code constants

Status code

CONTINUE

100

SWITCHING_PROTOCOLS

101

Ok

OK

200

Created

CREATED

201

Accepted

ACCEPTED

202

NonAuthoritativeInformation

NON_AUTHORITATIVE_INFORMATION

203

NoContent

NO_CONTENT

204

ResetContent

RESET_CONTENT

205

PartialContent

PARTIAL_CONTENT

206

MultiStatus

MULTI_STATUS

207

MULTIPLE_CHOICES

300

MovedPermanently

MOVED_PERMANENTLY

301

Found

FOUND

302

SeeOther

SEE_OTHER

303

NotModified

NOT_MODIFIED

304

USE_PROXY

305

TemporaryRedirect

TEMPORARY_REDIRECT

307

BadRequest

BAD_REQUEST

400

Unauthorized

UNAUTHORIZED

401

PAYMENT_REQUIRED

402

Forbidden

FORBIDDEN

403

NotFound

NOT_FOUND

404

MethodNotAllowed

METHOD_NOT_ALLOWED

405

NotAcceptable

NOT_ACCEPTABLE

406

PROXY_AUTHENTICATION_REQUIRED

407

RequestTimeout

REQUEST_TIMEOUT

408

Conflict

CONFLICT

409

Gone

GONE

410

LENGTH_REQUIRED

411

PreconditionFailed

PRECONDITION_FAILED

412

EntityTooLarge

REQUEST_ENTITY_TOO_LARGE

413

UriTooLong

REQUEST_URI_TOO_LONG

414

UnsupportedMediaType

UNSUPPORTED_MEDIA_TYPE

415

REQUESTED_RANGE_NOT_SATISFIABLE

416

ExpectationFailed

EXPECTATION_FAILED

417

UnprocessableEntity

UNPROCESSABLE_ENTITY

422

Locked

LOCKED

423

FailedDependency

FAILED_DEPENDENCY

424

TooManyRequest

TOO_MANY_REQUEST

429

InternalServerError

INTERNAL_SERVER_ERROR

500

NotImplemented

NOT_IMPLEMENTED

501

BadGateway

BAD_GATEWAY

502

ServiceUnavailable

SERVICE_UNAVAILABLE

503

GatewayTimeout

GATEWAY_TIMEOUT

504

HttpVersionNotSupported

HTTP_VERSION_NOT_SUPPORTED

505

InsufficientStorage

INSUFFICIENT_STORAGE

507

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.30.178