play的路由,参考:routes
GET /clients/{id}Client.show
第一个字段为HTTP请求方式,常用的有:GET, POST, PUT, DELETE, HEAD等;若设为*号,则可以匹配任意方式的请求
第二个字段为url Pattern,上例可对/clients/123及/clients/abc等匹配,也可通过正则来进行更严格的匹配,如/clients/{<[0-9]+>id}则仅能匹配id字段为数字的请求;而/clients/{<[a-z]{4,10}>id}则可匹配小写且长度在4与10范围内的Id;如/clients/?即可匹配/clients/也可匹配/clients。
第三个字段为java的action方法,该方法必须为Controller类的public static void 类型的,其所在的Controller类必须位于包controllers中,且必须为play.mvc.Controller类的子类;该字段也可以直接用状态码替换,如GET/favicon.ico404;用于直接响应404;此外,还可以为此字段传递常量参数,如GET/homeApplication.page(id: "home"),等价于:GET/pages/{id}Application.page,均会调用public static void page(String id)方法。
在routes文档中可定义变量来存放公共数据,如:%{java code}%用于定义变量,${param name}来引用变量,举例:
%{context = play.configuration.getProperty('context', '')}%
GET ${context}Secure.login
路由优先级:在routes文档中的匹配规则为非贪婪的,即若匹配到若一个urlpattern,则不再对剩下的urlpattern进行匹配;
在第三个字段中,若想直接跳转至某个静态页面,可使用staticDir或staticFile来指定静态文件目录或文件,如:
GET /publicstaticDir:public将响应public目录下的所有文件
GET /home staticFile:/public/html/index.html 将响应index.html文档
Reverse routing: generate some URL
The Router can be used to generate a URL from within a Java call. So you’re able to centralize in one only configuration file all your URI patterns, and then be more confident when refactoring your application.
For example, with this route definition:
GET /clients/{id} Clients.show
From your code, you can generate the URL able to invoke Clients.show:
map.put("id", 1541);
String url = Router.reverse("Clients.show", map).url;// GET /clients/1541
The URL generation is integrated into many of the framework’s components. You never should use the Router.reverse operation directly.
If you add parameters that are not included in the URI pattern, these parameters will be added to the query string:
map.put("id", 1541);
map.put("display", "full");
// GET /clients/1541?display=full
String url = Router.reverse("Clients.show", map).url;
The priority order is again used to find the most specific Route able to generate the URL.