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

前端 未结 1 1260
感情败类
感情败类 2021-01-21 04:56

I want to implement a setUserIfPresent() method that puts a user object into the context like Http.Context.current().args.put(\"user\", user);

相关标签:
1条回答
  • 2021-01-21 05:08

    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");
    }   
    
    0 讨论(0)
提交回复
热议问题