Implement your own object binder for Route parameter of some object type in Play scala

孤街醉人 提交于 2019-12-04 09:13:07

Use PathBindable to bind parameters from path rather than from query. Sample implementation for binding ids from path separated by comma (no error handling):

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;
    }

    ...

}

Sample path:

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

Sample routes entry:

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

Well, I have written up my own "MyOwnObject" binder now. Another way of implementing PathBindable to bind an object.

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)
 }
}
}

I'm not sure if it works for binding data in the path part of a URL, but you may want to read the docs on QueryStringBindable if you're able to accept your data as query params.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!