源https://www.playframework.com/documentation/2.5.x/RequestBinders#/conf/routes
自定义路由
Play提供了一套机制绑定来自路径或者查询的string参数的类型。
PathBindable
PathBindable
允许来自URL路径的对象;这意味着我们能够定义像/user/3这样的路由来调用下面的action:
controller
public Result user(User user){
return ok(user.name);
}
用户参数将自动提取URL路径中id,例如,下面的路由定义
/conf/routes
GET /user/:user controllers.BinderApplication.user(user: javaguide.binder.models.User)
实现了PathBindable
接口的类型T都能绑定为路径的参数。它定义了抽象方法bind
(绑定来自路径的值)和unbind
(从一个值中建立路径片段)
例如下面的类
public class User implements PathBindable<User> {
public Long id;
public String name;
}
一个binder绑定路径中:id参数的简单的例子
@Override
public User bind(String key, String id) {
// findById meant to be lightweight operation
User user = findById(new Long(id));
if (user == null) {
throw new IllegalArgumentException("User with id " + id + " not found");
}
return user;
}
@Override
public String unbind(String key) {
return String.valueOf(id);
}
在这个例子中,findById
方法被用来获取User实例。
注意:在真正的application中,这个方法应该是轻量级并且不涉及(e.g.数据库)接入,因为这段代码被调用在服务器IO线程并且必须是完全非阻塞的。因此你例如使用简单的对象识别符作为路径绑定,使用action组合获取真实值。
QueryStringBindable
query 字符串参数使用了相似的机制;类似/age的路由能够调用如下action
controller
public Result age(AgeRange ageRange){
return ok(String.valueOf(ageRange.from));
}
age参数可以自动从如/age?from=1&to=10的查询中抽取。
Any type T that implements QueryStringBindable can be bound to/from query one or more query string parameters. Similar to PathBindable, it defines abstract methods bind and unbind.
实现了QueryStringBindable
的任何类型T都可以被绑定到query的to/from参数。类似于PathBindable
,它定义了抽象方法bind
和unbind
。
例如这个类:
public class AgeRange implements QueryStringBindable<AgeRange> {
public Integer from;
public Integer to;
}
binder绑定:from
和:to
query参数的例子:
@Override
public Optional<AgeRange> bind(String key, Map<String, String[]> data) {
try{
from = new Integer(data.get("from")[0]);
to = new Integer(data.get("to")[0]);
return Optional.of(this);
} catch (Exception e){ // no parameter match return None
return Optional.empty();
}
}
@Override
public String unbind(String key) {
return new StringBuilder()
.append("from=")
.append(from)
.append("&to=")
.append(to)
.toString();
}
PS:稍后我们会讨论一下源码和实现