user1303559
user1303559

Reputation: 436

Playframework 2 - set session variable for any Action

I need call method for all requests - i tryed

object Global extends GlobalSettings {

    override def onRouteRequest(request: RequestHeader): Option[Handler] = {
        var test: String = request.session.get("test").getOrElse {
            request.session + ("test" -> "123")
            "000"
        }

        println(test)

        super.onRouteRequest(request)
    }

}

but I always see "000" in console and on page no cookies for domain

Update: new cookies added by ResponseHeader, but how I can add new cookie to RH before RH created? Exists there something like event listeners? Like postAction?

Upvotes: 2

Views: 2766

Answers (1)

Pere Villega
Pere Villega

Reputation: 16439

To add new Cookies you must add them in the Response tot he Session, like described in the documentation.

For example:

Ok("Hello World!").withSession(
  session + ("saidHello" -> "yes")
)

What you try to do doesn't make sense, as you are trying to add a Cookie after you receive a request from the browser (which contains the cookies the browser has). That means that if your code worked you'd always have that value in the session, always, so there would be no need to check the session for it as you would know it exists. Becoming redundant.

Upvotes: 1

Related Questions