首页 > 解决方案 > 比较:@RequestMapping 与 @PathVariable 的用法

问题描述

我想知道以上哪一项更好/正确/最常用或什么。第一个,使用 @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-mvcrequest-mapping

解决方案


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

您正在询问@RequestMappingpath之间的区别:value

就是想知道两者的区别。

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

使用时path

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

推荐阅读