在Java Play Framework 2.2.x中启用CORS

时间:2014-03-03 10:52:51

标签: java playframework cors playframework-2.2

我无法在Java Play 2.2.x中启用跨域

在Java Play 2.1.3中,此代码通过将其放入Global.java

来工作
public class Global extends GlobalSettings {

  private class ActionWrapper extends Action.Simple {
    public ActionWrapper(Action action) {
     this.delegate = action;
  }

    @Override
    public Result call(Http.Context ctx) throws java.lang.Throwable {
      Result result = this.delegate.call(ctx);
      Http.Response response = ctx.response();
      response.setHeader("Access-Control-Allow-Origin", "*");
      return result;
    }
  }

  @Override
  public Action onRequest(Http.Request request, java.lang.reflect.Method actionMethod) {
    return new ActionWrapper(super.onRequest(request, actionMethod));
  }

}

但是当我尝试在java play 2.2.x上编译时,它不再编译了。

编译错误消息:

Global.ActionWrapper不是抽象的,并且不会覆盖Action中的抽象方法调用(Context)...

java play 2.2.x是否有相同的代码?

感谢。

4 个答案:

答案 0 :(得分:7)

看起来像这样:

import play.GlobalSettings;
import play.libs.F.Promise;
import play.mvc.Action;
import play.mvc.Http;
import play.mvc.SimpleResult;

public class Global extends GlobalSettings {
    private class ActionWrapper extends Action.Simple {
        public ActionWrapper(Action<?> action) {
            this.delegate = action;
        }

        @Override
        public Promise<SimpleResult> call(Http.Context ctx) throws java.lang.Throwable {
            Promise<SimpleResult> result = this.delegate.call(ctx);
            Http.Response response = ctx.response();
            response.setHeader("Access-Control-Allow-Origin", "*");
            return result;
        }
    }

    @Override
    public Action<?> onRequest(Http.Request request, java.lang.reflect.Method actionMethod) {
        return new ActionWrapper(super.onRequest(request, actionMethod));
    }
}

答案 1 :(得分:6)

对于使用2.3.1+(撰写本文时)Play的任何人,现在Promise<Result>代替Promise<SimpleResult>

import play.GlobalSettings;
import play.libs.F.Promise;
import play.mvc.Action;
import play.mvc.Http;
import play.mvc.Result;

public class Global extends GlobalSettings {
    private class ActionWrapper extends Action.Simple {
        public ActionWrapper(Action<?> action) {
            this.delegate = action;
        }

        @Override
        public Promise<Result> call(Http.Context ctx) throws java.lang.Throwable {
            Promise<Result> result = this.delegate.call(ctx);
            Http.Response response = ctx.response();
            response.setHeader("Access-Control-Allow-Origin", "*");
            return result;
        }
    }

    @Override
    public Action<?> onRequest(Http.Request request, java.lang.reflect.Method actionMethod) {
        return new ActionWrapper(super.onRequest(request, actionMethod));
    }
}

答案 2 :(得分:2)

@alexhanschke提出的解决方案在请求抛出异常(内部服务器错误)时不起作用,因为当发生异常时不应用过滤器(请参阅https://github.com/playframework/playframework/issues/2429)。要解决这个问题,你必须包装一个scala类并返回结果,如下所示。请注意,这仍然需要指定的选项路由和控制器来处理选项请求。

在此处查看整个内容https://gist.github.com/tinusn/38c4c110f7cd1e1ec63f

import static play.core.j.JavaResults.BadRequest;
import static play.core.j.JavaResults.InternalServerError;
import static play.core.j.JavaResults.NotFound;

import java.util.ArrayList;
import java.util.List;

import play.GlobalSettings;
import play.api.mvc.Results.Status;
import play.libs.F.Promise;
import play.libs.Scala;
import play.mvc.Action;
import play.mvc.Http;
import play.mvc.Result;
import scala.Tuple2;
import scala.collection.Seq;

public class Global extends GlobalSettings {

  private class ActionWrapper extends Action.Simple {
    public ActionWrapper(Action<?> action) {
      this.delegate = action;
    }

    @Override
    public Promise<Result> call(Http.Context ctx) throws java.lang.Throwable {
      Promise<Result> result = this.delegate.call(ctx);
      Http.Response response = ctx.response();
      response.setHeader("Access-Control-Allow-Origin", "*");
      return result;
    }
  }

  /*
  * Adds the required CORS header "Access-Control-Allow-Origin" to successfull requests
  */
  @Override
  public Action<?> onRequest(Http.Request request, java.lang.reflect.Method actionMethod) {
    return new ActionWrapper(super.onRequest(request, actionMethod));
  }

  private static class CORSResult implements Result {
    final private play.api.mvc.Result wrappedResult;

    public CORSResult(Status status) {
      List<Tuple2<String, String>> list = new ArrayList<Tuple2<String, String>>();
      Tuple2<String, String> t = new Tuple2<String, String>("Access-Control-Allow-Origin","*");
      list.add(t);
      Seq<Tuple2<String, String>> seq = Scala.toSeq(list);
      wrappedResult = status.withHeaders(seq);
    }

    public play.api.mvc.Result toScala() {
      return this.wrappedResult;
    }
  }

  /*
  * Adds the required CORS header "Access-Control-Allow-Origin" to bad requests
  */
  @Override
  public Promise<Result> onBadRequest(Http.RequestHeader request, String error) {
    return Promise.<Result>pure(new CORSResult(BadRequest()));
  }

  /*
  * Adds the required CORS header "Access-Control-Allow-Origin" to requests that causes an exception
  */
  @Override
  public Promise<Result> onError(Http.RequestHeader request, Throwable t) {
    return Promise.<Result>pure(new CORSResult(InternalServerError()));
  }

  /*
  * Adds the required CORS header "Access-Control-Allow-Origin" when a route was not found
  */
  @Override
  public Promise<Result> onHandlerNotFound(Http.RequestHeader request) {
    return Promise.<Result>pure(new CORSResult(NotFound()));
  }

}

答案 3 :(得分:1)

另一种选择可能是使用Filters。目前只有Scala过滤器可用。但是,正如this post中为了简单地修改响应标头而指出的,您可以复制并粘贴以下内容以启用CORS。

package filters

import play.api.mvc._
import play.mvc.Http.HeaderNames
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

class EnableCORS extends Filter {
  def apply(f: (RequestHeader) => Future[Result])(rh: RequestHeader): Future[Result] = {
    val result = f(rh)
    result.map(_.withHeaders(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN -> "*"))
  }
}

然后在Global.java中添加过滤器:

@Override
public <T extends EssentialFilter> Class<T>[] filters() {
    return new Class[] {EnableCORS.class};
}