java PLAY框架学习笔记--routes

2 篇文章 0 订阅

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值