简体   繁体   中英

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. 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. 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. 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? 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.

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?

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();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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