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.
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 .
The default name for the cookie is PLAY_SESSION . This can be changed by configuring the key session. cookieName in application. conf.”
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 + "!"
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With