2014-10-16 52 views
5

好一些对象类型的路由参数自己的对象的粘合剂,我想,以取代从以下播放斯卡拉路线我的字符串PARAM到我自己的对象,说“为MyObject”实现在播放阶

From GET /api/:id controllers.MyController.get(id: String) 

To GET /api/:id controllers.MyController.get(id: MyOwnObject) 

任何如何做到这一点的想法将不胜感激。

回答

1

使用PathBindable从路径而不是从查询绑定参数。

public class CommaSeparatedIds implements PathBindable<CommaSeparatedIds> { 

    private List<Long> id; 

    @Override 
    public IdBinder bind(String key, String txt) { 
     if ("id".equals(key)) { 
      String[] split = txt.split(","); 
      id = new ArrayList<>(split.length + 1); 
      for (String s : split) { 
        long parseLong = Long.parseLong(s); 
        id.add(Long.valueOf(parseLong)); 
      } 
      return this; 
     } 
     return null; 
    } 

    ... 

} 

样品路径:

/data/entity/1,2,3,4 

样品路线条目:绑定来自路径ID用逗号(没有错误处理)分离的样品实施

GET /data/entity/:id controllers.EntityController.process(id: CommaSeparatedIds) 
1

我不确定它是否适用于绑定URL路径部分的数据,但如果您能够接受数据作为查询参数,则可能需要阅读QueryStringBindable上的文档。

4

好了,我已经写了现在我自己的“MyOwnObject”活页夹。另一种实现PathBindable来绑定对象的方法。

object Binders { 
    implicit def pathBinder(implicit intBinder: PathBindable[String]) = new PathBindable[MyOwnObject] { 
    override def bind(key: String, value: String): Either[String, MyOwnObject] = { 
    for { 
    id <- intBinder.bind(key, value).right 
    } yield UniqueId(id) 
} 

override def unbind(key: String, id: UniqueId): String = { 
    intBinder.unbind(key, id.value) 
} 
} 
}