Reputation: 1764
I'm looking for a single place in play framework 2.0.4 Java to modify the response.
Use case: Load some user object within the GlobalSettings.onRequest() method. That works, but I also need to set a cookie. Either I need access to the response(), or to the session(). Neither seems to be available in the onRequest() method. And there is no onResponse() method.
The only way I see right now is to call a method within every controller's method that returns a Result.
UPDATE The link I had originally posted here is dead now. Instead I've found this http://www.playframework.com/documentation/2.0/JavaActionsComposition which explains the same thing as the accepted answer below. Also, the comment about controller annotations is useful.
Upvotes: 2
Views: 1029
Reputation: 11274
In Java this seems to be much harder than in Scala. The basic idea is to wrap every action with a custom action that upon being called adds a header and calls the original method (the delegate
). This is the exact same mechanic as in Java action composition.
This solution works for me but isn't extensively tested, so please check if all of your actions still work.
import play.*;
import play.mvc.*;
public class Global extends GlobalSettings {
private class ActionWrapper extends Action.Simple {
public ActionWrapper(Action action) {
this.delegate = action;
}
@Override
public Result call(Http.Context ctx) throws java.lang.Throwable {
Result result = this.delegate.call(ctx);
Http.Response response = ctx.response();
response.setHeader("X-My-Header", "100");
return result;
}
}
@Override
public Action onRequest(Http.Request request, java.lang.reflect.Method actionMethod) {
return new ActionWrapper(super.onRequest(request, actionMethod));
}
}
Upvotes: 4