Search code examples
playframeworkplayframework-2.0locale

In play framework 2.x, how to add a global action/filter?


More specifically, I need to allow passing a locale in the url then change the locale. This should be a global behavior and must happen before any action is called so that the locale change takes effect from the current request.

The GlobalSettings.onRequest() does not have Http.Context bound yet and as far as I know it does not have an API for changing the locale at that stage.

I could have an action that changes the locale, but I do not know how to make it global so that all requests go to that action first,and I dont want to annotate every controller as it is very easily forgotten.

I'm using play framework 2.1.2, any pointer would be appreciated.


Solution

  • There are couple of options.

    1. You can annotate controller classes and use Action composition

    http://www.playframework.com/documentation/2.1.2/JavaActionsComposition

    1. Override the GlobalSettings.onRequest with following

       @Override
       public Action onRequest(Request request, Method actionMethod) {
           return new Action.Simple() {
              public Result call(Context ctx) throws Throwable {
                **//do your lang changing stuff**
                return delegate.call(ctx);
              }
           };
       }