[英]Long dynamic routes in play framework 2
我正在開發一個用於顯示汽車不同方面的應用程序。 該應用程序具有如下樹狀結構:
Country>Manufacturer>Model>Car_subsystem>Part
我希望這個結構能夠反映在瀏覽器的地址欄中:
http://localhost:9000/Germany/BMW/X6/Body/doors
目前,我使用play框架的動態路由,如下所示:
GET /:Country controllers.Application.controllerFunction(Country : String)
GET /:Country/:Manufacturer controllers.Application.controllerFunction(Country : String, Manufacturer : String)
等等
這是有效的,但我不喜歡將5或6個參數傳遞給我的所有控制器功能,只是為了讓路徑顯示得很漂亮! 還有其他方法嗎?
只需使用Dynamic parts spanning several /
如路由文檔中所述
路線:
GET /Cars/*path controllers.Application.carResolver(path)
行動(最簡單的方法)
public static Result carResolver(String path) {
Car car = Car.findByPath(path);
return ok(carView.render(car));
}
因此每輛車的場地path
應填充唯一的字符串ID,即: Germany/BMW/X6
,德國/梅賽德斯/ ASL`等。
當然,如果首先用斜杠分割path
arg會更好,這樣你就可以使用每個部分來顯示不同的視圖,'將'字符串'轉換為真實的對象ID等等。
public static Result carResolver(String path) {
String[] parts = path.split("/");
int partsLength = parts.length;
String country = (partsLength > 0) ? parts[0] : null;
String manufacturer = (partsLength > 1) ? parts[1] : null;
String carModel = (partsLength > 2) ? parts[2] : null;
// etc
switch (partsLength){
case 0: return countrySelect();
case 1: return allManufacturersIn(country);
case 2: return allModelsOf(manufacturer);
case 3: return singleViewFor(carModel);
// etc
}
return notFound("Didn't find anything for required path...");
}
提示:將字符串“轉換”為對象需要您在某個字段中搜索數據庫,因此有一些建議:
Country
應該有唯一的name
因為你可能不想擁有德國1,德國2等。 這種方法需要比通過數字ID搜索更多的時間,因此嘗試以某種方式緩存(mem-cache OR至少專用的DB表)解析的結果即:
Germany/BMW/X6 = Country: 1, Manufacturer: 2, CarModel: 3, action: "singleViewFor"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.