简体   繁体   中英

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.

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.

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);
}

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

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 .eg

class filter1 extends Filter {}

and apply filter1 to Global

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM