play framework(翻译)

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,它定义了抽象方法bindunbind
例如这个类:

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:稍后我们会讨论一下源码和实现

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值