要使用不同的路径来访问REST API中的相同资源

问题描述 投票:1回答:1

使用Spring-boot:MVC,REST API

背景:模型=学生>>年龄长(学生班级的属性之一)

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

  1. 通过学生证访问

`

@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”映射的模糊处理程序方法:{publicorg.springframework.http.ResponseEntitycom.example.restapi.controller.StudentController.getStudentAgeByName(java.lang.String),公共org.springframework.http.ResponseEntitycom.example.restapi.controller.StudentController.getStudentAge(java.lang.Long)}

java spring-boot rest spring-mvc spring-data-jpa
1个回答
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之类的非标识符字段>

© www.soinside.com 2019 - 2024. All rights reserved.