我在不同的控制器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.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))
}
}
}
正如前面的答案所暗示的,与直接共享控制器代码相比,在位于控制器下方的服务层中共享控制器代码更为有利。给定您的简单示例,但似乎可以做您正在做的事情。