Reputation: 5619
how can I set the respnose headers globally for my playframework project? I don't want to add the stuff for each REST method.
response().setHeader("Access-Control-Allow-Origin", "*");
response().setHeader("Allow", "*");
response().setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
response().setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent");
This is what I add to each Method at the Moment.
Thanks
Upvotes: 1
Views: 491
Reputation: 2105
Another way for 2.8 is this: https://www.playframework.com/documentation/2.8.x/JavaActionsComposition
You implement an annotation:
@With(VerboseAnnotationAction.class)
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface VerboseAnnotation {
boolean someValue() default true;
}
and an Action:
public class VerboseAnnotationAction extends Action<VerboseAnnotation> {
public CompletionStage<Result> call(Http.Request req) {
// This is you're taking value from the annotation
boolean parameterValue = configuration.someValue();
// decorate the response after calling the controller
return delegate.call(req)
.thenApply(r -> r.withHeader("SomeHeaderName", parameterValue));
}
}
Then you just use the annotation with the method or with the whole Controller class:
@VerboseAnnotation(false)
public Result verboseAnnotationIndex() {
return ok("It works!");
}
Upvotes: 1
Reputation: 18824
Play supports filters, it's a way of modifying HTTP requests/responses globally.
Something like:
public class GlobalHeaders extends Filter {
@Inject
public GlobalHeaders(Materializer mat) {
super(mat);
}
@Override
public CompletionStage<Result> apply(
Function<Http.RequestHeader, CompletionStage<Result>> nextFilter,
Http.RequestHeader requestHeader) {
return nextFilter.apply(requestHeader).thenApply(result -> {
return result.setHeader("Access-Control-Allow-Origin", "*")
.setHeader("Allow", "*")
.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS")
.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent");
});
}
}
Upvotes: 1