How I can pass a Map parameter as a GET param in url to Spring REST controller ?
Asked
Active
Viewed 1.4k times
4
-
See this question, and its answers: http://stackoverflow.com/questions/29387877/spring-mvc-requestmapping-how-to-catch-map-parameter – Ralph Nov 07 '15 at 10:01
-
Thanks, but I know how to catch it with a POST The question was about GET – alexanoid Nov 07 '15 at 10:03
2 Answers
8
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/

prash
- 896
- 1
- 11
- 18
5
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;
}
}
- Request: http://localhost:8080/demo?myMap[line1]=hello&myMap[line2]=world
- Output:
Command [myMap={line1=hello, line2=world}]
Tested with Spring Boot 1.2.7

Ralph
- 118,862
- 56
- 287
- 383
-
Thanks Ralph! What do you think about an approach where we will pass `@PathVariable List
map` and `map` will contain something like this: `12:34,833:73,90:25` In the controller logic we can split list elements by ":" and get key/value pairs.. – alexanoid Nov 07 '15 at 11:02 -
Why do you want to do this, when the "save" solution is so easy? I you want to map it by your own, then you should have a look at matix variables: http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-matrix-variables and http://www.captaindebug.com/2013/04/just-what-are-spring-32-matrix.html#.Vj3NmCvMaIg – Ralph Nov 07 '15 at 11:18
-
because currently I have a following mapping `@RequestMapping(value = "/criteria/{criteriaIds}` where `criteriaIds` is a `@PathVariable List
criteriaIds`. Right now I need to add double weight to some of `criteriaId` in criteriaIds list. – alexanoid Nov 07 '15 at 11:28