Can I set cookies before returning to Play Framework 2?

I know that when the action returns, I can set the cookies to Ok(...).withCookies(...) . 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 has to send them back.

+4
source share
1 answer

I do this only as an exercise, and also in order to show that the Play Framework is very flexible and does not limit you in any sense. I realized how to do this exclusively from the source code of the game, it is very clean and easy to read. This is NOT the preferred way to work with cookies or even with the HttpRequest object on Play. Since Jatin suggested that you decode your cookies into appropriate models, transfer these models to your services, and then convert the results of your services to play.api.mvc.Result, thereby preserving the separation of the layers of your web page and business logic.

Here's the code (you can see that the Headers object is not intended to be used that 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) 
+5
source

Source: https://habr.com/ru/post/1495591/


All Articles