SpringMVC数据绑定二(List、Set和Map类型)

1.List类型绑定

//联系信息类 用户类的子属性
public class ContactInfo {
    private String phone;
    private String address;
    //getting and setting............
}
//用户类
public class User {
    private String name;
    private Integer age;
    private ContactInfo contactInfo;
    
    //getting and setting............
    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + ", contactInfo=" + contactInfo + "]";
    }
}
//List<User> 集合的包装类
public class UserListForm {
    private List<User> users;

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

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

    @Override
    public String toString() {
        return "UserListForm [users=" + users + "]";
    }
}
//controller方法
//http://127.0.0.1:8080/SpringMVC/list?users[0].name=Tom&users[0].age=20&users[1].name=Lucy&users[1].age=25&users[1].contactInfo.phone=10086
@RequestMapping(value="list")
    @ResponseBody
    public String list(UserListForm userListForm) {
        return userListForm.toString();
    }

结果显示:

注意:若参数中users[20] 则生成的list对应的size为21

 

2.Set


//Set<User> 集合的包装类
public class UserSetForm {
    private Set<User> users;

    public UserSetForm() {
        //必须初始化,如若没有则报500错误Cannot get element with index 0 from Set of size 0
   //getPropertyValue(AbstractNestablePropertyAccessor.java:661)中做判断。抛出异常
users = new LinkedHashSet<>(); users.add(new User()); users.add(new User()); } public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } @Override public String toString() { return "UserSetForm [users=" + users + "]"; } }

 

@RequestMapping(value="set")
    @ResponseBody
    public String set(UserSetForm userSetForm) {
        return userSetForm.toString();
    }

 

访问方式和list一样:但是必须在声明的时候初始化,有几个对象初始化几个

3、Map

//Map<String,User> users 包装类
public class UserMapForm {
    private Map<String,User> users;

    public Map<String, User> getUsers() {
        return users;
    }

    public void setUsers(Map<String, User> users) {
        this.users = users;
    }

    @Override
    public String toString() {
        return "UserMapForm [users=" + users + "]";
    }
}

 

//TODO:http://127.0.0.1:8080/SpringMVC/map?users["x"].name=Tom&users["x"].age=10&users["y"].name=Lucy
    @RequestMapping(value="map")
    @ResponseBody
    public String map(UserMapForm userMapForm) {
        return userMapForm.toString();
    }

 

 

posted @ 2017-10-19 22:13  watermelonBan  阅读(4213)  评论(0编辑  收藏  举报