播放2.3 Java - 在所有响应中设置标头

时间:2014-07-15 08:56:20

标签: java playframework playframework-2.3

我将Play 2.3.0与Java 8一起使用,并希望在所有请求中设置一些标题。

我已经针对Scala的类似问题找到了Stackoverflow-answers,但我没有设法将此示例转换为Java世界:

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)
}
  }
}

我的尝试:

@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 个答案:

答案 0 :(得分:4)

最后我使用ActionComposition对我来说效果很好。

我必须用这样的一行来注释每个控制器:

@With(Headers.class)
public class MyController extends Controller {
.... }

...并像这样编写Action(伪代码):

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);
    }
}