问题
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