Play 2.2.1 Java: Whats the equivalent of @before filters from play 1.X?

一个人想着一个人 提交于 2019-12-20 02:51:35

问题


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.

With Play1 I create a BaseController that invokes this method before all requests (@Before filter) and extended all other controllers from this one.

How to achieve something like this in play2 using Java API?

Seems like there is something for Scala but for Java? http://www.playframework.com/documentation/2.2.x/ScalaHttpFilters

Cheers


回答1:


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.

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


来源:https://stackoverflow.com/questions/20072380/play-2-2-1-java-whats-the-equivalent-of-before-filters-from-play-1-x

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