Lion
Lion

Reputation: 271

How to apply a global filter in playframework

When using @before, it is only used in one class. How do I apply a global filter in playframework? So that one filter is used for all controller classes.

Upvotes: 10

Views: 6763

Answers (4)

user3231931
user3231931

Reputation: 331

It's not a good solution to extend a base controller for all of your controllers and have the @Before in the base controller.

You can extends the filter or essensialfilter .e.g.

class filter1 extends Filter {}

and apply filter1 to Global

Upvotes: 0

Christopher Davies
Christopher Davies

Reputation: 4551

I did this very thing by handling incoming requests globally in the GlobalSettings class:

This describes the class: http://www.playframework.org/documentation/2.0/JavaGlobal

This describes the method you'd want to override. http://www.playframework.org/documentation/2.0/JavaInterceptors

Here's an example of how I used it in my own project (of course, this is a simplified version of what you're looking for):

@Override
public play.mvc.Action onRequest(play.mvc.Http.Request request, java.lang.reflect.Method method) {
    if (request.path().startsWith("/secret/locked")) {
        return new Action.Simple() {
            @Override
            public Result call(play.mvc.Http.Context ctx) throws Throwable {
                return redirect(routes.Application.forbidden());
            }
        };
    }

    return super.onRequest(request, method);
}

Upvotes: 2

niels
niels

Reputation: 7309

You can simply use PlayPlugin for this issue. See here for more details.

Upvotes: 1

Codemwnci
Codemwnci

Reputation: 54904

A simple solution is to extend a base controller for all of your controllers and have the @Before in the base controller.

The other option (and the better solution, as it is more flexible) is to use the @With annotation. The example on the play documentation is

Example:

public class Secure extends Controller {

    @Before
    static void checkAuthenticated() {
        if(!session.containsKey("user")) {
            unAuthorized();
        }
    }
}    

And on another Controller:

@With(Secure.class)
public class Admin extends Application {

    ...

}

This means the Admin controller will process all the interceptors (@Before, @After, @Finally) contained within the Secure controller.

Upvotes: 6

Related Questions