简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM