【问题标题】:config same route path for 2 methods that receive different params为接收不同参数的 2 个方法配置相同的路由路径
【发布时间】:2014-03-26 17:22:52
【问题描述】:

我有一个控制器,它有一些功能。

我的问题是我想做:

GET     /v1.0/products          @controllers.ProductController.getProductsByCategory(lang: String ?="en_US", t:String, cat:String, start: Int ?=0, maxresults:Int ?=100, sort:String  ?="rank", order:String ?="asc")  
GET     /v1.0/products          @controllers.ProductController.getProducts(lang: String ?="en_US", t: String, ids: String)

我在控制器中有两个功能:

def getProducts(lang: String, t: String, ids: String) = Action { ... code.. }

def getProductsByCategory(lang: String, t: String, cat:String, start: Int, maxResults:Int, sort:String, order:String) = Action { ... Code ...}

这不起作用。我必须像这样定义路线:

GET     /v1.0/products/bycategory           @controllers.ProductController.getProductsByCategory(lang: String ?="en_US", t:String, cat:String, start: Int ?=0, maxresults:Int ?=100, sort:String  ?="rank", order:String ?="asc")  
GET     /v1.0/products          @controllers.ProductController.getProducts(lang: String ?="en_US", t: String, ids: String)

有没有办法在路径中不添加“bycategory”来实现这一点?

谢谢

【问题讨论】:

    标签: scala playframework playframework-2.0 scala-2.10


    【解决方案1】:

    您不能使用具有相同路径的两个路由类型(感谢 Haris,他已经写过),但您可以更好地使用路由器,我会使用就像(伪代码)

    GET /products                 getAllProducts()
    GET /products/:catId          getProductsByCat(catId)
    GET /products/:catId/:id      getSingleProductWithinCat(catId, id)
    

    所以你将拥有即/products > /products/toys > /products/toys/rc-plane

    当然你仍然可以添加你的可选参数:

    GET /products/toys?start=10&maxresults=250
    

    记住这些是GET路线=,普通用户会尝试手动修改以加快搜索速度是正常的,所以如果/products/toys/rc-plane不满足他,他会先尝试升级到再次/products/toys

    【讨论】:

      【解决方案2】:

      一种方法是使用一种方法来获取产品,例如

      GET     /v1.0/products          @controllers.ProductController.getProducts(lang: String ?="en_US", t:String, cat:String ?= "", start: Int ?=0, maxresults:Int ?=100, sort:String  ?="rank", order:String ?="asc")
      

      您将默认类别设置为无/空。如果您需要所有产品,请将其保留为默认值,例如

      http://myhost/v1.0/products
      

      如果您需要类别

      http://myhost/v1.0/products?category=hotsauces
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-17
        • 1970-01-01
        • 2018-01-04
        • 1970-01-01
        • 2021-03-05
        相关资源
        最近更新 更多