简体   繁体   English

在Play框架中的另一个控制器中重用一个控制器的结果

[英]Reusing the Result of a Controller in another Controller in the Play framework

Apologies if this has been answered already - I've had a look and can't find anything. 抱歉,如果已经回答-我看了看,什么也找不到。

Using the Play framework, I have defined two controllers - one is a public API that returns JSON, and one is a consumer of this API which presents the JSON as HTML. 使用Play框架,我定义了两个控制器-一个是返回JSON的公共API,一个是该API的使用者,该API将JSON呈现为HTML。 Eg my routes file look as follows: 例如,我的路线文件如下所示:

GET     /foos       controllers.App.foos() #produces HTML
GET     /api/foos   controllers.API.foos() #produces JSON

A requirement of the project is that our data should only be accessed via our public API. 该项目的要求是只能通过公共API访问我们的数据。 Therefore, the way that I'd like to implement this is to have App.foos() invoke API.foos() , parse the JSON result, and pass it to a template to be rendered. 因此,我想要实现的方法是让App.foos()调用API.foos() ,解析JSON结果,并将其传递给要呈现的模板。 For example: 例如:

public App extends Controller {
  public static Result foos() {
    Result result = API.foos();
    // TODO: get the JSON out of the result object
  }
}

Can anyone tell me how I can extract the JSON from the result object? 谁能告诉我如何从结果对象中提取JSON? I can get the body of the object as an Enumerator using ((SimpleResult)result.getWrappedResult()).body() , but I am still unclear how I can get out the JSON. 我可以使用((SimpleResult)result.getWrappedResult()).body()作为枚举器获取对象的((SimpleResult)result.getWrappedResult()).body() ,但是我仍然不清楚如何获取JSON。

Because I am new to the Play framework, perhaps I am going about this wrong and there is an easier/better way to do this? 因为我是Pl​​ay框架的新手,所以也许我正在解决这个错误,并且有更简单/更好的方法来做到这一点?

Many thanks in advance, James 预先感谢,詹姆斯

The easiest way would be to expose the underlying method. 最简单的方法是公开基础方法。

public Api extends Controller {

  public static Result foos() {
    Ok(foosJson());
  }

  public static JsValue foosJson() {
    // ...
  }
}

public App extends Controller {

  public static Result foos() {
    JsValue json = API.foosJson();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM