使用Spring-boot:MVC,REST API
背景:模型=学生>>年龄长(学生班级的属性之一)
我可以定义两个URL路径来访问特定学生的年龄吗?示例:
`
@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);
`
@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)}
因为/{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
之类的非标识符字段>