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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With