本文使用SpringMVC版本:

org.springframework:spring-webmvc:4.3.9.RELEASE

 对应spring boot版本为:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>
    </dependencies>

 

---------------------------2021年5月13日新增-------start-----------------

源码下载:https://gitee.com/flyingfree/springmvc-demo.git 

注意示例中的springboot版本不是最新的,如果用新版注意看评论区

---------------------------2021年5月13日新增-------end-----------------

 

正文:

写法及说明(示例代码的类上的注解是@RestController,所以方法上不需要添加@ResponseBody):

    @RequestMapping("/hello")
    public String test(String name,@RequestBody List<ForListReceive> list) {
        /**
         * 接收List的条件
         * 1、使用JSON格式数据,如[{"a":"a","b":"b"}] 放在RequestBody中传递
         * 2、RequestHeader中需要有 Content-Type: application/json;charset=utf8
         * 3、需要在参数前加上@RequestBody
         */

        System.out.println(list.get(0).getA());
        return list.size()+":"+name;
    }

    @RequestMapping("/hi")
    public String hi(@RequestParam("list") List<String> list) {
        /**
         * 接收List<String>
         * 1、Request Parameters中list=a,b,c 
         * 2、必须写上@RequestParam("list")
         */
        System.out.println(list.get(0));
        return list.size()+"";
    }

    @RequestMapping("/hey")
    public String hey(String[] list) {
        /**
         * 接收数组
         * 1、Request Parameters中list=a,b,c 即可成功接收
         */
        System.out.println(list[0].toString());
        System.out.println(list[1].toString());
        return list.length+"";
    }

 

ForListReceive.java:

public class ForListReceive {
    String a;
    String b;

    public String getA() {
        return a;
    }

    public void setA(String a) {
        this.a = a;
    }

    public String getB() {
        return b;
    }

    public void setB(String b) {
        this.b = b;
    }
}

 

相关文章: