Loading

SpringMVC获取集合类型参数

方法一

将集合参数包装成POJO。

  1. 包装类
public class Vo {
    private List<User> users;

    @Override
    public String toString() {
        return "Vo{" +
                "users=" + users +
                '}';
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }
}

tips: user的属性不要使用包装类型,如Integer,不然会报错。

  1. controller:
@RequestMapping("/list.do")
    @ResponseBody
    //获取集合类型参数时,集合中类对象user中的属性不能使用包装类型,如Integer
    public ModelAndView doList(Vo vo){
        ModelAndView modelAndView = new ModelAndView();
        List<User> users = vo.getUsers();
        users.forEach(u-> System.out.println(u));
        modelAndView.addObject("users",users);
        modelAndView.setViewName("target");
        return modelAndView;
    }
  1. 初始界面和结果界面
<form action="user/list.do" method="post">
        姓名1:<input type ="text" name="users[0].name"><br>
        年龄1:<input type ="text" name="users[0].age"><br>
        姓名2:<input type ="text" name="users[1].name"><br>
        姓名2:<input type ="text" name="users[1].age"><br>
        <input type="submit" value="提交">
    </form>





<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <table border="1">
        <thead>
            <tr>
                <td>姓名</td>
                <td>年龄</td>
            </tr>
        </thead>
        <tbody>
            <c:forEach var="users" items="${users}" varStatus="s">
                <tr>
                    <td>${users.name}</td>
                    <td>${users.age}</td>
                </tr>
            </c:forEach>
        </tbody>
    </table>
</body>
</html>

方法二:

@RequestMapping("/ajax.do")
    @ResponseBody
    public void doListOfAjax(@RequestBody List<User> users){
        users.forEach(u-> System.out.println(u));
    }






<script>
    let array = new Array();
    array.push({"name":"黄振聪","age":21})
    array.push({"name":"黄大大","age":22})
    $(function () {
        $(".btn").click(function () {
            $.ajax({
                url:"user/ajax.do",
                type:"post",
                data:JSON.stringify(array),
                dataType:"json",
                contentType:"application/json;charset=utf-8"
            })
        })
    })
</script>
posted @ 2021-08-22 22:31  IamHzc  阅读(299)  评论(0编辑  收藏  举报