Playframework 2 - set session variable for any Act

2019-07-17 11:41发布

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?

1条回答
我只想做你的唯一
2楼-- · 2019-07-17 12:01

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.

查看更多
登录 后发表回答