使用分页的Play路由最佳实践是什么?

3

我是Play 2 (Scala)的新手。我需要使用分页来输出列表中的成员。这很容易,除了分页部分。

在我的路由文件中,我有我的搜索:

GET        /find/thing/:type        controllers.Application.showType(type: String)

如果我想把整个列表都输出到页面上,那么这种方法是可行的。

但是,如果我想要分页呢?我可以这样做 -

GET        /find/thing/:type/:page        controllers.Application.showType(type: String, page: Int)

但是如果用户只输入“myurl.com/find/thing/bestThing”而没有输入页面,会发生什么呢?很明显,当应该自动“默认”为页面1时,会出现错误。

有没有一种方法来设置这些参数的默认值?如果没有,那么最佳实践是什么呢?

谢谢!

2个回答

3

两个选项:

  1. declare both routes you mentioned (first using parameter with fixed value), then you can use untrail trick globally, in such case it will redirect your /find/thing/something/ to /find/thing/something (page=1)
  2. You can use parameters with default values, then your route will be like:

    GET /find/thing/:type  controllers.Application.showType(type: String, page: Int ?= 1)
    
生成的URL将会是这样的:
/find/thing/something?page=123

谢谢您,我们选择了您的答案,因为它有多个好的解决方案。 - Steve

2

您可以使用查询字符串参数而不是路径参数来表示页面编号。查询字符串参数允许您在缺少参数时提供默认值。

GET   /find/thing/:type      controllers.Application.showType(type: String, page: Int ?= 1)

你可以这样使用它们:
/find/thing/bestThing?page=3    // shows page 3

/find/thing/bestThing           // shows page 1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接