问题
I am using Play 2.3.0 together with Java 8 and want to set some headers in all requests.
I have already found Stackoverflow-answers for the similar question for Scala, but I didn't manage to convert this example into the Java world:
import play.api._
import play.api.mvc._
import play.api.Play.current
import play.api.http.HeaderNames._
object Global extends GlobalSettings {
def NoCache(action: EssentialAction): EssentialAction = EssentialAction { request =>
action(request).map(_.withHeaders(PRAGMA -> "no-cache"))
}
override def onRouteRequest(request: RequestHeader): Option[Handler] = {
if (Play.isDev) {
super.onRouteRequest(request).map { handler =>
handler match {
case a: EssentialAction => NoCache(a)
case other => other
}
}
} else {
super.onRouteRequest(request)
}
}
}
My try:
@Override
public Handler onRouteRequest(final Http.RequestHeader request) {
Handler handler = super.onRouteRequest(request);
if(handler instanceof EssentialAction) {
return new EssentialAction() // ?!? - how to do that in Java 8?
} else {
return handler;
}
}
回答1:
Finally I use ActionComposition which works pretty well for me.
I have to annotate every Controller wth a line like this:
@With(Headers.class)
public class MyController extends Controller {
.... }
...and write the Action like this (Pseudo-code):
public class Headers extends Action.Simple {
public F.Promise<Result> call(final Http.Context ctx) throws Throwable {
ctx.response().setHeader("Access-Control-Allow-Origin", "*");
return delegate.call(ctx);
}
}
来源:https://stackoverflow.com/questions/24753876/play-2-3-java-set-header-on-all-responses