【问题标题】:How to return a result from an Action in Java Play Framework?如何从 Java Play 框架中的动作返回结果?
【发布时间】:2019-06-10 00:29:30
【问题描述】:

我所有的控制器都使用我创建的 CheckDowntimeAction

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

正如预期的那样,在每个请求中,CheckDowntimeAction 都会打印“我在这里!”。但是我如何在CheckDowntimeAction 中中止,以便如果站点关闭,我会返回我在CheckDowntimeAction 中创建的自己的结果?

public class CheckDowntimeAction extends play.mvc.Action.Simple {
    @Override
    public CompletionStage<Result> call(Http.Request req) {
        logger.info("I'm here!");

        // just move along, nothing to see here
        return delegate.call(req);
    }
}

这可行,但它会打印停机时间结果之后 MyController 已经完成运行。我希望它在控制器完成之前运行

public class CheckDowntimeAction extends play.mvc.Action.Simple {
    @Override
    public CompletionStage<Result> call(Http.Request req) {
        if (downtime) {
           Result r = badRequest("Site is down");

           // before Play 2.7, this would have been:
           // return F.Promise.pure(badRequest(r));

           return delegate.call(req).thenApply(result -> r);
        }

        // just move along, nothing to see here
        return delegate.call(req);
    }
}

请注意,这是使用 Java Play 2.7,它使用请求而不是上下文,并且 F.Promise 不再可用。见https://www.playframework.com/documentation/2.7.x/JavaHttpContextMigration27

【问题讨论】:

    标签: java controller frameworks action playback


    【解决方案1】:

    根据https://www.playframework.com/documentation/2.5.1/api/java/play/libs/F.Promise.html 中的文档,F.Promise 已弃用,它说要改用CompletableFuture.completedFuture。 Play 2.7 的变化是 F.Promise 最终被完全删除。

    我认为正确的 Play 2.7 方式是:return CompletableFuture.completedFuture(r);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      • 2015-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多