Playframework 2-为任何动作设置会话变量 [英] Playframework 2 - set session variable for any Action

查看:99
本文介绍了Playframework 2-为任何动作设置会话变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要所有请求的调用方法-我尝试过

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)
    }

}

但是我总是在控制台中看到"000",并且在页面上没有域的Cookie

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

更新:ResponseHeader添加了新的cookie,但是如何在创建RH之前将新的cookie添加到RH? 是否存在类似事件侦听器的内容?喜欢postAction吗?

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?

推荐答案

要添加新的Cookie,您必须将其添加到会话响应中,如

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

例如:

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

您尝试执行的操作没有任何意义,因为您在收到来自浏览器的请求(包含浏览器具有的cookie)之后尝试添加Cookie.这意味着,如果您的代码能够正常工作,那么您将始终在会话中拥有该值,因此您就不必像检查会话那样检查它的存在了.变得多余.

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.

这篇关于Playframework 2-为任何动作设置会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆