Addition of an attribute to a Play request makes a new instance of request?

杀马特。学长 韩版系。学妹 提交于 2019-12-11 08:29:23

问题


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.

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)

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...


回答1:


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

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

EDIT:

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

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


来源:https://stackoverflow.com/questions/49742712/addition-of-an-attribute-to-a-play-request-makes-a-new-instance-of-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!