java PLAY框架學習筆記--routes

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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章