简体   繁体   English

我可以在Play Framework 2中返回操作之前设置cookie吗?

[英]Can I set cookies before returning an action in Play Framework 2?

I know I can set cookies in Ok(...).withCookies(...) when returning an action. 我知道我可以在返回动作时在Ok(...).withCookies(...)设置cookie。 However I wonder if there is a way to set some cookies by manipulating the request object. 但是我想知道是否有办法通过操纵request对象来设置一些cookie。 So that I can set some cookies in my models and my controller just need to send them back. 这样我就可以在我的模型中设置一些cookie,而我的控制器只需要将它们发回去。

I'm doing this only as exercise, and also to show that Play framework is very flexible and it doesn't limit you in any sense. 我这样做只是作为练习,并且还表明Play框架非常灵活,并且它在任何意义上都不会限制你。 I figured out how to do this purely from Play source code, it is very clean and easy to read. 我想出了如何纯粹从Play源代码中做到这一点,它非常干净且易于阅读。 This is NOT the preferred way to work with cookies or indeed with HttpRequest object in Play. 不是使用cookie或在Play中使用HttpRequest对象的首选方式。 As Jatin suggested you should decode your cookies to proper models, pass those models to your services and then convert result of your services to play.api.mvc.Result, thus keeping your http and business logic layers separated. 正如Jatin建议您将cookie解码为正确的模型,将这些模型传递给您的服务,然后将服务结果转换为play.api.mvc.Result,从而保持您的http和业务逻辑层分离。

Here's the code( you can see that Headers object is not intended to be used this way): 这是代码(您可以看到Headers对象不打算以这种方式使用):

import play.api.http.HeaderNames.COOKIE

val cookies = Cookies(request.headers.get(COOKIE)).cookies

val myCookies = cookies + ("cookieName" -> Cookie("cookieName", "cookieValue"))

val headersMap = request.headers.toMap

val myHeaderMap = headersMap +  
      (COOKIE -> Seq(Cookies.encode(myCookies.values.toSeq)))

val myHeaders = new play.api.mvc.Headers {
  val data:Seq[(String, Seq[String])] = myHeaderMap.toSeq
}

val modifiedRequest = request.copy(headers = myHeaders)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM