Map parameter as GET param in Spring REST controller

北城余情 提交于 2019-12-20 02:15:55

问题


How I can pass a Map parameter as a GET param in url to Spring REST controller ?


回答1:


There are different ways ( but a simple @RequestParam('myMap')Map<String,String> does not work)

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




回答2:


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("AAA");//apple
    String banana = map.get("BBB");//banana

    return apple + banana;
}

Request

/demo?AAA=apple&BBB=banana

Source -- https://reversecoding.net/spring-mvc-requestparam-binding-request-parameters/



来源:https://stackoverflow.com/questions/33581329/map-parameter-as-get-param-in-spring-rest-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!