Search code examples
playframeworkplay-framework-2.7

How to set header in all responses in Play! framework 2.7 (Java)


In older Play! versions (like 2.3) it was possible to modify the header of all responses like

public class WithMyPHeaderAction extends Action<WithMyPHeader> {

    @Override
    public CompletionStage<Result> call(Context ctx) {
        ctx.response().setHeader("any", "value");
        return delegate.call(ctx);
    }
}

How do I do this with Play! 2.7 without deprecation (ctx.response() is deprecated since 2.7), in Java?


Solution

  • You don't need an Action to do this. In the controller you can just:

    return ok().withHeader("any", "value");
    

    If you have to do this in an Action same thing:

    @Override
    public CompletionStage<Result> call(Http.Request req) {
        return delegate.call(req).thenApply(r -> r.withHeader("any", "value"));
    }
    

    I'm using play.mvc.Action.Simple for the Action. Also I've tested this on Play 2.8.1, should work on Play 2.7 too.