[英]Play 2.2.1 Java: Whats the equivalent of @before filters from play 1.X?
I want to implement a setUserIfPresent () method that puts a user object into the context like Http.Context.current().args.put("user", user); 我想实现一个setUserIfPresent ()方法,该方法将用户对象放入上下文中,如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. 应在每个控制器方法之前应用此方法,以便视图可以访问用户的隐式访问权限。
With Play1 I create a BaseController that invokes this method before all requests (@Before filter) and extended all other controllers from this one. 使用Play1,我创建一个BaseController , 在所有请求(@Before filter) 之前 调用此方法,并从此扩展所有其他控制器。
How to achieve something like this in play2 using Java API? 如何使用Java API在play2中实现这样的功能?
Seems like there is something for Scala but for Java? 看起来像Scala有什么东西但是对于Java? http://www.playframework.com/documentation/2.2.x/ScalaHttpFilters http://www.playframework.com/documentation/2.2.x/ScalaHttpFilters
Cheers 干杯
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; 虽然你可以在“传统的”webapp框架方式中使用过滤器( 或拦截器 ),但Play首选方式似乎绝对是组成自定义Action
方法; see the documentation on Action Composition . 请参阅有关Action Composition的文档。
If you follow their style, you'll define a new Action
implementation like this: 如果你遵循他们的风格,你将定义一个新的Action
实现,如下所示:
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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.