Play 2.2.1 Java: Whats the equivalent of @before f

2019-02-24 12:01发布

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条回答
狗以群分
2楼-- · 2019-02-24 12:32

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");
}   
查看更多
登录 后发表回答