如何将Map参数作为GET param在url中传递给Spring REST控制器?
答案 0 :(得分:2)
有不同的方法(但简单的@RequestParam('myMap')Map<String,String>
不起作用)
(IMHO)最简单的解决方案是使用命令对象,然后您可以在URL中使用[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}]
使用Spring Boot 1.2.7进行测试
答案 1 :(得分:2)
只需在注释后添加一个Map对象,就可以将所有请求参数绑定到Map中:
@RequestMapping("/demo")
public String example(@RequestParam Map<String, String> map){
String apple = map.get("AAA");//apple
String banana = map.get("BBB");//banana
return apple + banana;
}
请求
/ demo?AAA = apple&BBB = banana
来源-https://reversecoding.net/spring-mvc-requestparam-binding-request-parameters/