如何在播放框架中的动作中获得被调用动作的响应

how to get the response of called Action within an Action in play framework

我在不同的控制器中有两个 Action ActionA 和 ActionB 我在 ActionA 中调用 ActionB 并且我想在 ActionA 中获得它的(ActionB)响应是否可能?我怎样才能实现这个请帮助这是我的代码

class ControllerA extends Controller{

def ActionA = Action { implicit request =>
    var jsonRequest = request.body.asJson.get
    val uuid = (jsonRequest \ "uuid").as[String]
    log.info("in ActionA" + uuid)
    val controllerB= new ControllerB
    val actionB=controllerB.ActionB.apply(request)
    //here i want to get the response of ActionB and return this response as the response of ActionA whether its OK or InternelServerError
    Ok("i want to show the response of ActionB")
    }
}

class ControllerB extends Controller{
def ActionB = Action { implicit request =>
    var jsonRequest = request.body.asJson.get
    val uuid = (jsonRequest \ "uuid").as[String]
    log.info("in ActionB " + uuid)
    try {
      Ok("i am ActionB with id {}"+uuid)
    } catch {
      case e: Exception =>
        log.error("Exception ", e)
        val status = Http.Status.INTERNAL_SERVER_ERROR
        InternalServerError(Json.obj("status" -> status, "msg" -> ServerResponseMessages.INTERNAL_SERVER_ERROR))
    }
  }
}

请帮忙

如果您将控制器部署在单个 JVM 中,我认为您可以从 ActionB 中提取一个函数并在两个控制器之间共享代码。如果您将控制器部署在两个不同的 JVM 中,在这种情况下您需要使用 Web 服务客户端库来查询端点。只是我的两分钱。

在游戏中,2.2 和 2.3 控制器通常是 object 而不是 class,所以我将您的控制器更改为对象。在较新版本的游戏控制器中 类 使用 Guice 框架注入。

由于操作调用是异步的,您需要将 ActionA 更改为 Action.async。以下是我所做的更改:

object ControllerA extends Controller{

  def ActionA = Action.async { implicit request =>
    var jsonRequest = request.body.asJson.get
    val uuid = (jsonRequest \ "uuid").as[String]
    log.info("in ActionA" + uuid)
    ControllerB.ActionB(request)
  }
}

object ControllerB extends Controller{
  def ActionB = Action { implicit request =>
    var jsonRequest = request.body.asJson.get
    val uuid = (jsonRequest \ "uuid").as[String]
    log.info("in ActionB " + uuid)
    try {
      Ok("i am ActionB with id {}"+uuid)
    } catch {
      case e: Exception =>
        log.error("Exception ", e)
        val status = Http.Status.INTERNAL_SERVER_ERROR
        InternalServerError(Json.obj("status" -> status, "msg" -> ServerResponseMessages.INTERNAL_SERVER_ERROR))
    }
  }
}

正如前面的回答所暗示的,与直接共享控制器代码相比,在位于控制器下方的服务层中共享控制器代码要有利得多。考虑到您的简单示例,尽管做您正在做的事情似乎没问题。