I am trying to add a simple string to a play session, but it is just not working. For testing I wrote a little controller function that first adds a string to the session and afterwards, it prints all elements the session contains, but it’s always empty.
def foo = Action { request =>
request.session + ("token", "foobar")
request.session.data.foreach{ keyVal => println("\tkey value pair: " + keyVal._1 + ", " + keyVal._2)}
Ok("just a test")
}
What did I do wrong? Do I need to activate something via application.conf or something else?
Actually, a session is an immutable structure as well.
It’s true that the
sessionobject that is stored in therequestone has a+method, this latter is respecting the immutability paradigm by returning a new instance ofSession. Keeping therequest.sessionunchanged.Thinking a step further, we can assert on the fact that an updated session has only a sense when reused in another request-response transaction…
So the way to update a session is to update it while building the response (
Resultin Play), like that:This will add the new session field in your cookie, that will be available in the next transaction (i.e. request-response).