How I can pass a Map parameter as a GET param in url to Spring REST controller ?
It’s possible to bind all request parameters in a Map just by adding a Map object after the annotation:
@RequestMapping("/demo")
public String example(@RequestParam Map<String, String> map){
String apple = map.get("APPLE");//apple
String banana = map.get("BANANA");//banana
return apple + banana;
}
Request
/demo?APPLE=apple&BANANA=banana
Source -- https://reversecoding.net/spring-mvc-requestparam-binding-request-parameters/
There are different ways (but a simple @RequestParam('myMap')Map<String,String>
does not work - maybe not true anymore!)
The (IMHO) easiest solution is to use a command object then you could use [key]
in the url to specifiy the map key:
@Controller
@RequestMapping("/demo")
public class DemoController {
public static class Command{
private Map<String, String> myMap;
public Map<String, String> getMyMap() {return myMap;}
public void setMyMap(Map<String, String> myMap) {this.myMap = myMap;}
@Override
public String toString() {
return "Command [myMap=" + myMap + "]";
}
}
@RequestMapping(method=RequestMethod.GET)
public ModelAndView helloWorld(Command command) {
System.out.println(command);
return null;
}
}
Command [myMap={line1=hello, line2=world}]
Tested with Spring Boot 1.2.7
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