Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload Controller Method in Java Spring

Tags:

java

spring

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?

like image 269
tinaheidinger Avatar asked May 21 '15 17:05

tinaheidinger


1 Answers

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) {     ... } 
like image 197
Sotirios Delimanolis Avatar answered Sep 22 '22 10:09

Sotirios Delimanolis