使用Spring-boot:MVC,REST API
背景:Model = Student >> Long age(学生班级的属性之一)
我可以定义两个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”映射的模糊处理程序方法:{public org.springframework.http.ResponseEntity com.example.restapi.controller.StudentController.getStudentAgeByName(java.lang.String),public org.springframework.http.ResponseEntity com。 example.restapi.controller.StudentController.getStudentAge(java.lang.Long)}
由于/{name}/age
和/{id}/age
路径相同。在这里,{name}
或是{id}
路径变量。
因此,您尝试使用相同的路径映射两个不同的处理程序方法。这就是为什么春天给你错误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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句