如何使用 Scala 读取 Play-Framework 中 cookie 的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6249387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I read the value of a cookie in the Play-Framework with Scala?
提问by Jay Taylor
How can I read the value of a cookie in my controller in the Play-Framework with Scala?
如何在 Scala 的 Play-Framework 中读取控制器中 cookie 的值?
In my controller I have this:
在我的控制器中,我有这个:
println(Http.Request.current().headers.get("cookie"))
And the output is this:
输出是这样的:
[csrftoken=011d7cfe84915ee9897c8c6079d49d5a; test=value]
And I'm hoping there is a better way of accessing the value of "test" other than parsing the string.. ;)
而且我希望有一种更好的方法来访问“test”的值而不是解析字符串.. ;)
回答by Codemwnci
You can access the cookie using the cookieobject on the HTTP Request, rather than getting it in raw format from the header. Look at the API herefor more info.
您可以使用cookieHTTP 请求上的对象访问 cookie ,而不是从标头中以原始格式获取它。查看此处的 API了解更多信息。
You should be able to just do:
你应该能够做到:
Http.Request.current().cookies.get("test")
Http.Request.current().cookies.get("test")
回答by Sivailango
You can get the cookie value in scala template using @request.cookies.get("email").value.
您可以使用@request.cookies.get("email").value 在 Scala 模板中获取 cookie 值。
If you want to check its not null, @if(request.cookies.get("email") != null) {}
如果你想检查它是否为空,@if(request.cookies.get("email") != null) {}
回答by Ricky Boy
I am using Play 2.6.19 with Scala and I fetch as below;
我在 Scala 中使用 Play 2.6.19,我获取如下;
val leadToken = request.cookies.get("lead_token") match {
case Some(cookie) => cookie.value
case None => ""
}

