I have a controller that needs to behave differently with different URL parameters. Something like this:
@RequestMapping(method = RequestMethod.GET) public A getA(@RequestParam int id, @RequestParam String query) { ... } @RequestMapping(method = RequestMethod.GET) public A getA(@RequestParam int id) { ... }
But this doesn't seem to work, I get the following exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map '[controller name]' bean method
Is there a way that the application chooses the method depending on the URL params?
Indicate in the mapping which params should be present
@RequestMapping(method = RequestMethod.GET, params = {"id", "query"}) public A getA(@RequestParam int id, @RequestParam String query) { ... } @RequestMapping(method = RequestMethod.GET, params = {"id"}) public A getA(@RequestParam int id) { ... }
Since Spring MVC version 4.3, the new @GetMapping
, @PostMapping
, and similar annotations also have this params
element you can use
@GetMapping(params = {"id"}) public A getA(@RequestParam int id) { ... }
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