Play 2.3 Java - Set header on all responses

我与影子孤独终老i 提交于 2019-12-11 00:29:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!