【问题标题】:To use different paths to access same resource in REST API在 REST API 中使用不同的路径访问相同的资源
【发布时间】:2020-07-22 04:02:45
【问题描述】:

使用 Spring-boot:MVC , REST API

背景:Model=Student >> Long age(Student类的属性之一)

我可以定义两个 URL 路径来访问特定学生的年龄吗?示例:

  1. 通过学生 ID 访问

`

@GetMapping("/{id}/age")
public ResponseEntity<String> getStudentAge(@PathVariable Long id) {
    String age = studentService.retrieveAgeById(id);
    return new ResponseEntity<String>(age, HttpStatus.OK);
}

`

SQL 查询(使用 id ):

@Query("select d.id, d.age from Student d where d.id=:id")
String findAgeById(Long id);
  1. 按学生姓名访问年龄

`

   @GetMapping("/{name}/age")
        public ResponseEntity<String>  getStudentAgeByName(@PathVariable String name) {
            String age = studentService.retrieveAgeByName(name);
            return new ResponseEntity<String>(age, HttpStatus.OK);
        }

`

SQL 查询(使用名称):

@Query("select d.name, d.age from Student d where d.name=:name")
    String findAgeByName(String name);

此方法产生此错误:

出现意外错误(类型=内部服务器错误, 状态=500)。为“/2/age”映射的模棱两可的处理程序方法:{public org.springframework.http.ResponseEntity com.example.restapi.controller.StudentController.getStudentAgeByName(java.lang.String), 公共 org.springframework.http.ResponseEntity com.example.restapi.controller.StudentController.getStudentAge(java.lang.Long)}

【问题讨论】:

    标签: java spring-boot rest spring-mvc spring-data-jpa


    【解决方案1】:

    因为/{name}/age/{id}/age 是同一个路径。 这里,{name}{id} 是一个路径变量。

    所以你试图用相同的路径映射两个不同的处理程序方法。这就是为什么 spring 给你错误Ambiguous handler methods mapped

    你可以试试这个方法解决

    @GetMapping("/age/{id}")
    public ResponseEntity<String> getStudentAge(@PathVariable Long id) {
        String age = studentService.retrieveAgeById(id);
        return new ResponseEntity<String>(age, HttpStatus.OK);
    }
    
    @GetMapping("/age/name/{name}")
    public ResponseEntity<String>  getStudentAgeByName(@PathVariable String name) {
         String age = studentService.retrieveAgeByName(name);
         return new ResponseEntity<String>(age, HttpStatus.OK);
    }
    

    但最好将请求参数用于非标识符字段,例如name

    【讨论】:

    • @SrikanthKb 如果您发现任何有帮助的解决方案也可以投票给他们。
    • 对不起,我忘了回复这个。感谢您的解决方案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多