Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set cookies before returning an action in Play Framework 2?

I know I can set cookies in Ok(...).withCookies(...) when returning an action. However I wonder if there is a way to set some cookies by manipulating the request object. So that I can set some cookies in my models and my controller just need to send them back.

like image 357
NSF Avatar asked Aug 06 '13 18:08

NSF


People also ask

How do you set content type explicitly on play?

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 .

What is the default session cookie name set by the Play framework?

The default name for the cookie is PLAY_SESSION . This can be changed by configuring the key session. cookieName in application. conf.”

What is action in play framework?

What is an Action? Most of the requests received by a Play application are handled by an action. An action is basically a Java method that processes the request parameters, and produces a result to be sent to the client. public Result index(Http. Request request) { return ok("Got request " + request + "!"


1 Answers

I'm doing this only as exercise, and also to show that Play framework is very flexible and it doesn't limit you in any sense. I figured out how to do this purely from Play source code, it is very clean and easy to read. This is NOT the preferred way to work with cookies or indeed with HttpRequest object in Play. As Jatin suggested you should decode your cookies to proper models, pass those models to your services and then convert result of your services to play.api.mvc.Result, thus keeping your http and business logic layers separated.

Here's the code( you can see that Headers object is not intended to be used this way):

import play.api.http.HeaderNames.COOKIE

val cookies = Cookies(request.headers.get(COOKIE)).cookies

val myCookies = cookies + ("cookieName" -> Cookie("cookieName", "cookieValue"))

val headersMap = request.headers.toMap

val myHeaderMap = headersMap +  
      (COOKIE -> Seq(Cookies.encode(myCookies.values.toSeq)))

val myHeaders = new play.api.mvc.Headers {
  val data:Seq[(String, Seq[String])] = myHeaderMap.toSeq
}

val modifiedRequest = request.copy(headers = myHeaders)
like image 150
vitalii Avatar answered Sep 23 '22 06:09

vitalii