在Spring REST控制器中将参数映射为GET参数
问题内容:
如何将Map参数作为url中的GET参数传递给Spring REST控制器?
问题答案:
有不同的方法(但简单的方法@RequestParam('myMap')Map<String,String>
不起作用)
(IMHO)最简单的解决方案是使用命令对象,然后可以[key]
在url中使用以指定映射键:
@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;
}
}
- 请求:http:// localhost:8080 / demo?myMap [line1] = hello&myMap [line2] = world
- 输出:
Command [myMap={line1=hello, line2=world}]
通过Spring Boot 1.2.7测试