[英]Play 2.5.x java - How to call a controller method from another controller?
我有兩個控制器A和B。我想從B調用A的create方法。我該怎么做?
public class A extends Controller {
public Result create() {
...
}
}
public class B extends Controller {
public Result create() {
// How to call A.create() ??
}
}
在Play 2.5中,由於DI(Google Guice)是內置的,因此我們可以注入所需的控制器並直接調用其方法!
public class A extends Controller {
public Result create(String param) {
...
}
}
public class B extends Controller {
@Inject
private A a;
public Result create() {
a.create("param");
// do other stuff and return result
}
}
我認為您需要定義另一個包含邏輯的方法,然后從控制器的方法中調用該方法。 像這樣的東西:
public class SampleController extends Controller{
@BodyParser.Of(BodyParser.Json.class)
public Result createMessage(){
JsonNode json = request().body().asJson();
return ok(createMessageLogic(json.get("id").asLong()));
}
public String createMessageLogic(long id){
return "the id is " + id;
}
}
這樣,您可以輕松地將您的控制器注入另一個控制器並調用邏輯方法。 但是,您可以考慮在控制器類旁邊保留一個服務層,這更清潔。
只需創建共享邏輯的靜態方法,並使用它為兩個操作構建Result
,它將自動包含request()
,這是最簡單的示例:
public class A extends Controller {
public Result create(String param) {
return shared("A role", param);
}
public static Result shared(String role, String param) {
String msg = "Path: " + request().path();
msg += ", role is: `" + role + "`";
msg += (param == null)
? " and has no param"
: ", with param: " + param;
return ok(msg);
}
}
public class B extends Controller {
public Result create() {
return controllers.A.shared("B role", null);
}
}
關於參數
請注意,實際上,您唯一需要在A.create(...)
和B.create(...)
中解析的String param
是路徑部分( A
路徑中的String param
),或者可能是一些可選參數,每個參數中都進行了硬編碼在示例中的role
。
其他(例如request
, session
, cache
,DB數據等)可以(應該)在shared()
方法中提取。
提示:如果傳遞到所需的PARAMS數量shared()
方法大,你不想創造這樣的怪物
controllers.A.shared(null, null, null, null, null, null, null, null, "foo");
只需創建Map<String, Object>
集合並一次傳遞所有內容,或創建專用瞬態模型,該模型將所有值保存在適當的字段中。 當將許多值傳遞到常見的Twirl模板時,第二個選項也是我的最愛。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.