首页 > 解决方案 > 如何从 Java Play 框架中的动作返回结果?

问题描述

我所有的控制器都使用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

标签: javacontrollerframeworksactionplayback

解决方案


根据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);


推荐阅读