Play 2.2.1 Java:与 play 1.X 中的 @before 过滤器等价的是什么? [英] Play 2.2.1 Java: Whats the equivalent of @before filters from play 1.X?
问题描述
我想实现一个 setUserIfPresent() 方法,将用户对象放入上下文中,如 Http.Context.current().args.put("user", 用户);
I want to implement a setUserIfPresent() method that puts a user object into the context like Http.Context.current().args.put("user", user);
应该在每个控制器方法之前应用此方法,以便视图可以访问用户的隐式访问权限.
This method should be applied before every controller method so that views have access implicit access to the user.
使用 Play1,我创建了一个 BaseController,它调用这个方法before所有请求(@Before 过滤器)和扩展来自这个控制器的所有其他控制器.
With Play1 I create a BaseController that invokes this method before all requests (@Before filter) and extended all other controllers from this one.
如何在 play2 中使用 Java API 实现类似的功能?
似乎有一些适用于 Scala 但适用于 Java 的东西?http://www.playframework.com/documentation/2.2.x/ScalaHttpFilters
Seems like there is something for Scala but for Java? http://www.playframework.com/documentation/2.2.x/ScalaHttpFilters
干杯
推荐答案
虽然你可以使用过滤器 (or Interceptors) 在传统"的 webapp 框架方式中,Play 首选方式似乎肯定是组合自定义 Action
方法;请参阅有关动作组合的文档.
While you could use filters (or Interceptors) in the "traditional" webapp framework way, the Play-preferred way seems to definitely be to compose custom Action
methods; see the documentation on Action Composition.
如果您遵循他们的风格,您将定义一个新的 Action
实现,如下所示:
If you follow their style, you'll define a new Action
implementation like this:
public class UserContextInjectingAction extends play.mvc.Action.Simple {
public F.Promise<SimpleResult> call(Http.Context ctx) throws Throwable {
Logger.info("Injecting user data into context " + ctx);
injectUser(ctx); // Written by you
return delegate.call(ctx);
}
}
你最终会得到如下所示的控制器代码:
And you'd end up with controller code that looks like this:
@With(UserContextInjectingAction.class)
public static Result showHomePage() {
return ok("Welcome");
}
这篇关于Play 2.2.1 Java:与 play 1.X 中的 @before 过滤器等价的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!