Question

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?

Was it helpful?

Solution

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

}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top