What are Play 2.0 equivalents of @Before and @After from Play 1.2?
Asked Answered
V

2

9

When I was using Play 1.2, I was able to annotate some methods inside any controller with @Before or @After (and others...) in order to execute a method before or after each request inside this controller.

How can I do this in Play 2.0?

I read a little bit about the Global object, but it doesn't seem to be what I am looking for. Also, action composition seems way too complex for what I want to do. I hope to see something simpler.

Any ideas?

Vigilant answered 2/10, 2012 at 0:57 Comment(0)
P
8

Unfortunately, you'll have to use action composition for the @Before, and there is no equivalent for the @After.

For the @After, I'd write my own after method at the end of end action; something like this:

public static Result index() {
    ....
    Result result = ...;
    return after(result);
}

protected static Result after(Result result) {
    ...
    Result afterResult = ...,
    return afterResult

}
Purveyor answered 2/10, 2012 at 6:30 Comment(0)
P
4
public class Logging {

    @With(LogAction.class)
    @Target({ElementType.TYPE, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Logs {

    }

    public static class LogAction extends Action<Logs> {

        private void before(Context ctx) { 
            System.out.println("Before action invoked");
        } 

        private void after(Context ctx) { 
            System.out.println("After action invoked");
        } 

        public F.Promise<Result> call(Http.Context context) throws Throwable {
            before(context); 
            Promise<Result> result = delegate.call(context);
            after(context);
            return result; 
        }
    }

}

Annotate with @Logs in your controller.

Perni answered 19/6, 2015 at 5:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.