播放2.2.1 Java:相当于播放1.X的@before过滤器? [英] Play 2.2.1 Java: Whats the equivalent of @before filters from play 1.X?

查看:75
本文介绍了播放2.2.1 Java:相当于播放1.X的@before过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个 setUserIfPresent ()方法,该方法将用户对象放入上下文,如Http.Context.current()。args.put(user ,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过滤器)和扩展所有其他控制器。

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

干杯

推荐答案

当你可以使用传统webapp框架方式的过滤器(或拦截器), Play首选方式似乎绝对是组成自定义 Action 方法;请参阅有关 Action Composition 的文档。

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");
}   

这篇关于播放2.2.1 Java:相当于播放1.X的@before过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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