如何在Action in play框架中获取被调用Action的响应

时间:2017-03-10 09:31:09

标签: java scala playframework playframework-2.2 playframework-2.3

我在不同的控制器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))
    }
  }
}

请帮助

2 个答案:

答案 0 :(得分:1)

在游戏中,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))
    }
  }
}

正如之前的答案所提到的,在控制器下面的服务层中共享控制器代码而不是直接共享控制器代码更为有利。鉴于你的简单例子,虽然你正在做你正在做的事情似乎没问题。

答案 1 :(得分:0)

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