ale*_*oid 4 spring spring-mvc spring-restcontroller
如何将 Map 参数作为 url 中的 GET 参数传递给 Spring REST 控制器?
只需在注释后添加一个 Map 对象,就可以将所有请求参数绑定到一个 Map 中:
@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;
}
Run Code Online (Sandbox Code Playgroud)
要求
/demo?APPLE=apple&BANANA=香蕉
来源——https: //reversecoding.net/spring-mvc-requestparam-binding-request-parameters/
有不同的方法(但简单的@RequestParam('myMap')Map<String,String>方法不起作用 - 也许不再正确!)
(恕我直言)最简单的解决方案是使用命令对象,然后您可以[key]在 url 中使用来指定地图键:
@控制器
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
Command [myMap={line1=hello, line2=world}]使用 Spring Boot 1.2.7 测试
| 归档时间: |
|
| 查看次数: |
10855 次 |
| 最近记录: |