[英]To use different paths to access same resource in REST API
Working with Spring-boot:MVC, REST API使用 Spring-boot:MVC, REST API
Background: Model=Student >> Long age (one of the attributes of Student class)背景:Model=Student >> Long age(Student类的属性之一)
Can I define two URL paths to access the age of a particular student?我可以定义两个 URL 路径来访问特定学生的年龄吗? Example:
例子:
` `
@GetMapping("/{id}/age")
public ResponseEntity<String> getStudentAge(@PathVariable Long id) {
String age = studentService.retrieveAgeById(id);
return new ResponseEntity<String>(age, HttpStatus.OK);
}
` `
SQL query (using id ): 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 (using name): SQL 查询(使用名称):
@Query("select d.name, d.age from Student d where d.name=:name")
String findAgeByName(String name);
This method is producing this error:此方法产生此错误:
There was an unexpected error (type=Internal Server Error, status=500).
出现意外错误(类型=内部服务器错误,状态=500)。 Ambiguous handler methods mapped for '/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)}
Ambiguous handler methods mapped for '/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)}
Because of /{name}/age
and /{id}/age
are same path.因为
/{name}/age
和/{id}/age
是相同的路径。 Here, {name}
or {id}
is a path variable.这里,
{name}
或{id}
是路径变量。
So you are trying to do map two different handler method with the same path.因此,您正在尝试使用相同的路径执行 map 两种不同的处理程序方法。 That's why spring gives you error
Ambiguous handler methods mapped
这就是为什么 spring 给你错误
Ambiguous handler methods mapped
You can try this way to resolve this您可以尝试这种方式来解决这个问题
@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);
}
But it's better to use request param for non identifer field like name
但最好将请求参数用于
name
等非标识符字段
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.