Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 943
Lion Avatar asked Jan 07 '11 08:01

Lion


2 Answers

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.

like image 185
Codemwnci Avatar answered Nov 10 '22 08:11

Codemwnci


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);
}
like image 2
Christopher Davies Avatar answered Nov 10 '22 06:11

Christopher Davies