I am trying to build a REST application in Spring where I have a requirement to delete resources on the basis of certain path variables.
For example, I want to delete resource(s) by id
@DeleteMapping("resources/{id}")
or by name
@DeleteMapping("resources/{name}")
But when I do the above, I get the error
java.lang.IllegalStateException: Ambiguous handler methods
As I understand, Servlets can't tell whether 123
in path /resources/123
represents an ID or a name and hence the ambiguity.
How shall then I design my REST endpoint where a DELETE happens based on some parameter or maybe a combination of parameters?
Spring can't distinguish between the two request as your mapping is ambiguous.
You could try using a query parameter for the second request. So it could look like following :
@DeleteMapping("/hello/{id}")
public String deleteById(@PathVariable("id") Long id) {
return "Delete by id called";
}
@DeleteMapping("/hello")
public String deleteByName(@RequestParam(value = "name") String name) {
return "Delete by name called";
}
Requests like DELETE http://localhost:8080/hello/1 will be handled by deleteById
Requests like DELETE http://localhost:8080/hello?name=deleteMe will be handled by deleteByName.
Or you could add name query param to the same method and if your query param is not null you could delete by name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With