簡體   English   中英

如何在游戲框架中的動作中獲得被叫動作的響應

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

我在不同的控制器ActionA和ActionB中有兩個Action,我在ActionB中調用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.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))
    }
  }
}

正如前面的答案所暗示的,與直接共享控制器代碼相比,在位於控制器下方的服務層中共享控制器代碼更為有利。 考慮到您的簡單化示例,可以執行您正在做的事情。

如果您將控制器部署在單個JVM中,我認為您可以從ActionB中提取一個函數並在兩個控制器之間共享代碼。 如果將控制器部署在兩個不同的JVM中,則在這種情況下,您需要使用Web服務客戶端庫來查詢端點。 只是我的兩分錢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM