【问题标题】:Some doubts about the use of parameters into a request toward a REST web service?对在向 REST Web 服务的请求中使用参数的一些疑问?
【发布时间】:2015-09-20 10:31:04
【问题描述】:

我是 Spring 和 REST Web 服务的新手,我有以下教程,该教程展示了如何使用 Spring MVC 实现 RESTful Web 服务。

所以,进入控制器类我有这个方法:

@Controller
@RequestMapping("/api/categories")
public class CategoryRestController {

    @RequestMapping
    @ResponseBody
    public CategoryList getCategories(@RequestParam("start") int start, @RequestParam("size") int size ) {
        List<Category> categoryEntries = categoryService.findCategoryEntries(start, size);
        return new CategoryList(categoryEntries);

    }

}

此方法处理对资源/api/categories的HTTP GET请求,并将检索到的列表返回为JSON格式(我认为这取决于内容协商:如果调用者把 Accept 头作为 JSON 方法返回 JSON 格式的结果,对吗?)

顺便说一句,我怀疑与教程中显示的 HTTP 请求有关,事实上它确实如此:

http://localhost:8080/springchocolatestore/api/categories?start=0&size=2

由前面的控制器方法处理以返回 JSON 格式的分页列表(可能是hude),实际上我检索到以下输出:

{
  "categories": [
    {
      "links": [
        {
          "rel": "self",
          "href": "http://localhost:8080/springchocolatestore/api/categories/1",
          "variables": [],
          "templated": false,
          "variableNames": []
        }
      ],
      "name": "Truffles",
      "description": "Truffles",
      "id": {
        "rel": "self",
        "href": "http://localhost:8080/springchocolatestore/api/categories/1",
        "variables": [],
        "templated": false,
        "variableNames": []
      }
    },
    {
      "links": [
        {
          "rel": "self",
          "href": "http://localhost:8080/springchocolatestore/api/categories/2",
          "variables": [],
          "templated": false,
          "variableNames": []
        }
      ],
      "name": "Belgian Chocolates",
      "description": "Belgian Chocolates",
      "id": {
        "rel": "self",
        "href": "http://localhost:8080/springchocolatestore/api/categories/2",
        "variables": [],
        "templated": false,
        "variableNames": []
      }
    }
  ]
}

好的,所以在请求中我通过 categories?start=0&size=2

指定分页参数

我的怀疑与这个参数的用户有关。据我了解(但可能是错误的),使用参数违反了 RESTful 原则。这是真的还是我错过了什么?

或者在这种特定情况下可能是有效的,因为参数没有指定对象(必须返回到我的 JSON 输出中),而只与某些选项相关?

我的意思是也许我不能使用参数来指定一个特定的对象,像这样:

// RETRIEVE THE PRODUCT WITH ID=1
http://localhost:8080/springchocolatestore/api/producs?product=1

所以我认为前面没有遵循 RESTfull 标准,因为我指定了一个带有参数的产品对象,而不是作为资源访问它,所以我必须这样做:

http://localhost:8080/springchocolatestore/api/producs/1

你能解释一下吗?

Tnx

【问题讨论】:

  • 你错了。没有什么 unRESTful 使用参数。
  • @JBNizet 哦,我信任你(我经常阅读你的评论,我知道你对软件架构有深入的了解)。但是使用参数来指定特定对象,难道不反对 RESTful 架构吗?
  • RESTful 与 URL 没有太大关系。但我同意路径变量一般用于标识特定资源,参数一般用于搜索或分页参数。
  • 好的,你的评论很清楚......如果你想作为回应(只需复制和粘贴它)我会接受:-)

标签: spring web-services rest spring-mvc spring-rest


【解决方案1】:

REST 与 URL 没有太大关系,使用请求参数也不是非 RESTful。

但我同意路径变量一般用于标识特定资源,参数一般用于搜索或分页参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 2017-03-10
    相关资源
    最近更新 更多