向 Play 请求添加属性会产生一个新的请求实例? [英] Addition of an attribute to a Play request makes a new instance of request?

查看:87
本文介绍了向 Play 请求添加属性会产生一个新的请求实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果像我一样,您来自 Java Servlet 世界,那么 Play 对请求属性的支持(最近在 2.6 版中引入)只是太久了.现在,我有机会详细了解它,但我想知道它是否可用.

If, like me, you're coming from the Java Servlet world, Play's support for request attributes (recently introduced in release 2.6) was only too long in coming. Now, that I've had a chance to look at it in some detail though, I wonder if it's usable.

来自文档(Scala)的逐字逐字:

Verbatim from the docs (Scala):

// Create a TypedKey to store a User object
object Attrs {
  val User: TypedKey[User] = TypedKey.apply[User]("user")
}
// Get the User object from the request
val user: User = req.attrs(Attrs.User)
// Put a User object into the request
val newReq = req.addAttr(Attrs.User, newUser)

我理解并欣赏不可变对象的功能思想,但是如果这个片段被解释为向请求添加属性的行为让我持有一个新请求,那么我该怎么办!?在回调的反应式世界中,Play 将请求传递给我的 代码,难道不是相反的想法吗?如果我不能在一个动作中附加一个属性,然后在错误处理程序中检查它,这有什么好处?希望我只是在这里遗漏了一些东西......

I get and appreciate functional idea of immutable objects, but if this snippet is to be interpreted as that the act of adding an attribute to a request leaves me holding a new request, then what am I to do with it!? In the reactive world of callbacks, isn't the idea that Play passes the requests to my code, not the other way around? If I can't attach an attribute in an action and then inspect it in the error handler, what good is this? Hopefully, I am just missing something here...

推荐答案

您通过过滤器将属性附加到请求.https://www.playframework.com/documentation/2.6.x/ScalaHttpFilters

You attach attributes to a request through a filter. https://www.playframework.com/documentation/2.6.x/ScalaHttpFilters

然后过滤器可以将 new 请求传递给框架,然后框架会将其提供给您的处理程序.

The filter can then pass along the new request to the framework, which will then give it to your handler.

将修改后的(新的)请求传回框架:

Passing the modified (new) request back to the framework:

...
nextFilter(requestHeader.addAttr(Attrs.User, newUser))
...

这篇关于向 Play 请求添加属性会产生一个新的请求实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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