[英]Long dynamic routes in play framework 2
I am developing an app for showing different aspects of cars. 我正在开发一个用于显示汽车不同方面的应用程序。 The app has a tree-like structure like this:
该应用程序具有如下树状结构:
Country>Manufacturer>Model>Car_subsystem>Part
I want this structure to be reflected in browser's address bar: 我希望这个结构能够反映在浏览器的地址栏中:
http://localhost:9000/Germany/BMW/X6/Body/doors
Currently, I do it with play framework's dynamic routing as below: 目前,我使用play框架的动态路由,如下所示:
GET /:Country controllers.Application.controllerFunction(Country : String)
GET /:Country/:Manufacturer controllers.Application.controllerFunction(Country : String, Manufacturer : String)
etc. 等等
This works, but I don't like passing around 5 or 6 parameters to all my controller functions just for the paths to be shown beautifully! 这是有效的,但我不喜欢将5或6个参数传递给我的所有控制器功能,只是为了让路径显示得很漂亮! Is there any other way?
还有其他方法吗?
Just use Dynamic parts spanning several /
as described in routing doc 只需使用
Dynamic parts spanning several /
如路由文档中所述
route: 路线:
GET /Cars/*path controllers.Application.carResolver(path)
Action (simplest approach) 行动(最简单的方法)
public static Result carResolver(String path) {
Car car = Car.findByPath(path);
return ok(carView.render(car));
}
so each car should have its field path
filled with unique string ID, ie: Germany/BMW/X6
, Germany/Mercedes/ASL` etc. 因此每辆车的场地
path
应填充唯一的字符串ID,即: Germany/BMW/X6
,德国/梅赛德斯/ ASL`等。
Of course it will be much better if you split the path
arg by the slash first so you can use each part for displaying different views, 'translate' strings to real object ID etc etc. 当然,如果首先用斜杠分割
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...");
}
TIP: "translating" strings to objects will require from you searching in DB by some field, so there's some advices: 提示:将字符串“转换”为对象需要您在某个字段中搜索数据库,因此有一些建议:
Country
should have unique name
as probably you don't want to have Germany 1, Germany 2 etc. Country
应该有唯一的name
因为你可能不想拥有德国1,德国2等。 This approach requires probably more time than searching by numeric ID's so try to cache somehow (mem-cache OR at least dedicated DB table) the result of resolving ie.: 这种方法需要比通过数字ID搜索更多的时间,因此尝试以某种方式缓存(mem-cache OR至少专用的DB表)解析的结果即:
Germany/BMW/X6 = Country: 1, Manufacturer: 2, CarModel: 3, action: "singleViewFor"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.