Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 623
Marc-François Avatar asked Oct 02 '12 00:10

Marc-François


People also ask

Is Play framework still used?

Play is rock-solid and used by hundreds of thousands of Java and Scala developers every month. Play is still extremely relevant to today's application and web development and has a passionate and very capable community around it ensuring that it has many good years left.

Which server does play internally use?

Play uses the Akka HTTP server backend to implement HTTP requests and responses using Akka Streams over the network. Akka HTTP implements a full server stack for HTTP, including full HTTPS support, and has support for HTTP/2. The Akka HTTP server backend is the default in Play.

What are the languages used by the Play framework?

Play web applications can be written in Scala or Java, in an environment that may be less Java Enterprise Edition-centric.


2 Answers

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

}
like image 113
ndeverge Avatar answered Sep 17 '22 08:09

ndeverge


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.

like image 42
Sivailango Avatar answered Sep 17 '22 08:09

Sivailango