在Spring REST控制器中将参数映射为GET参数

问题描述 投票:1回答:2

我如何将一个Map参数作为GET param在url中传递给Spring REST控制器?

spring spring-mvc spring-restcontroller
2个回答
1
投票

有不同的方式(但简单的@RequestParam('myMap')Map<String,String>不起作用)

(IMHO)最简单的解决方案是使用命令对象然后你可以在url中使用[key]来指定map键:

@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;
    }
}

用Spring Boot 1.2.7测试


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;
}

请求

/演示?AAA =苹果&BBB =香蕉

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

© www.soinside.com 2019 - 2024. All rights reserved.