Reputation: 27
Working with Spring-boot:MVC , REST API
Background: Model=Student >> Long age (one of the attributes of Student class)
Can I define two URL paths to access the age of a particular student? 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 ):
@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):
@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). 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)}
Upvotes: 1
Views: 741
Reputation: 18410
Because of /{name}/age
and /{id}/age
are same path.
Here, {name}
or {id}
is a path variable.
So you are trying to do map two different handler method with the same path. That's why spring gives you error 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
Upvotes: 1