Spring Mvc 页面传递数组到后台接收

1.定义一个简单的类 User.java

public class User {

    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

2.前端页面代码:

·   <form action="/user.front" method="post">
        <span>姓名1:</span><input type="text" name="name"/>

        <span>姓名2:</span><input type="text" name="name"/>
        <input type="submit" value="submit"/>
    </form>

3.提交时两个name需要作为数组当做参数传递.后台接收时需要做个处理:

  • 新建一个类UserModel,代码如下:
public class UserModel {

    private List<User> users;

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

    public UserModel (){}

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

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

4.此时前端代码name命名需改为

    <form action="/user.front" method="post">
        <span>姓名1:</span><input type="text" name="users[0].name"/>

        <span>姓名2:</span><input type="text" name="users[1].name"/>
        <input type="submit" value="submit"/>
    </form>

注意name中的users已UserModel.java的变量名一致;

5.UserController接收方式为:

    @RequestMapping("user.front")
    @ResponseBody
    public int test(UserModel user){
        System.out.println("user = " + user);;
        return 1;
    }

此时的参数名就是UserModel,就能成功接收到数据; 

posted @ 2018-04-16 18:40  如果屈原会编程  阅读(370)  评论(0编辑  收藏  举报