【问题标题】:Comparison: usage of @RequestMapping vs @PathVariable比较:@RequestMapping 与 @PathVariable 的用法
【发布时间】:2020-09-21 13:56:34
【问题描述】:

我想知道以上哪一项更好/正确/最常用或什么。第一个,使用@RequestMapping 中的值或另一个使用路径。

    @RequestMapping(value = { "/isbn/{isbnCode}" }, method = RequestMethod.GET)
    public ResponseEntity<?> findByIsbnCode(@PathVariable String isbnCode) {
        Book obj = service.findByIsbnCode(isbnCode);

        return ResponseEntity.ok().body(obj);
    }
// Request: http://localhost:8080/books/title?title=book_title

    @RequestMapping(method = RequestMethod.GET, path = { "/title" })
    public ResponseEntity<?> findByTitle(@RequestParam(value = "title") String title) {
        Book obj = service.findByTitle(title);

        return ResponseEntity.ok().body(obj);
    }
// Request: http://localhost:8080/books/isbn/978-84-663-4612-2

两者都有效。只是想找出两者之间的区别。

提前致谢!

【问题讨论】:

标签: spring-mvc request-mapping


【解决方案1】:

“URI 参数(由@PathVariable 表示的路径参数/变量)基本上用于标识一个或多个特定资源,而查询参数(或由@RequestParam 表示的请求参数)用于对这些资源进行排序/过滤。” 第一个示例使用路径变量,在这里您从 url 本身提取值,而在第二个示例中,您正在获取请求/查询参数。 参考: https://dzone.com/articles/understanding-the-uri-param-and-query-param-with-r https://blog.restcase.com/7-rules-for-rest-api-uri-design/#:~:text=URIs%20should%20follow%20a%20predictable,APIs%20are%20written%20for%20consumers.

【讨论】:

    【解决方案2】:

    JPA是Java Persistence API,与@RequestMapping无关;

    您正在询问@RequestMapping 的pathvalue 之间的区别:

    只是想找出两者之间的区别。

    pathvalue 元素是彼此的别名,从Spring Documentation 中我只能看到细微的差别:

    使用path时:

    • 还支持蚂蚁风格的路径模式(例如"/profile/**");
    • 可以使用占位符(例如"/${profile_path}")。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      • 2020-02-17
      • 2018-07-11
      • 2017-06-14
      • 2011-01-21
      • 1970-01-01
      相关资源
      最近更新 更多