如何为我的playframework项目全局设置respnose标头? 我不想为每个REST方法添加内容。
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");
这是我在片刻时添加到每个方法的内容。
由于
答案 0 :(得分:1)
播放支持filters,这是一种全局修改HTTP请求/响应的方法。
类似的东西:
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");
});
}
}
答案 1 :(得分:1)
2.8的另一种方法是:https://www.playframework.com/documentation/2.8.x/JavaActionsComposition
您实现注释:
@With(VerboseAnnotationAction.class)
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface VerboseAnnotation {
boolean someValue() default true;
}
和一个动作:
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));
}
}
然后,您只需在方法或整个Controller类中使用注释:
@VerboseAnnotation(false)
public Result verboseAnnotationIndex() {
return ok("It works!");
}