播放2.3 Java-在所有响应上设置标头 [英] Play 2.3 Java - Set header on all responses

查看:65
本文介绍了播放2.3 Java-在所有响应上设置标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Play 2.3.0与Java 8结合使用,并希望在所有请求中设置一些标头.

I am using Play 2.3.0 together with Java 8 and want to set some headers in all requests.

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

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

我的尝试:

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

推荐答案

最后,我使用 ActionComposition 对我来说很好.

Finally I use ActionComposition which works pretty well for me.

我必须用以下一行注释每个Controller:

I have to annotate every Controller wth a line like this:

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

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

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

这篇关于播放2.3 Java-在所有响应上设置标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆