一、基本数据类型的绑定
表单代码:
@RequestMapping(value = "/echo") @ResponseBody public String echo(String name){ return name; }
注意:
- 方法形参中的参数名要和前台传进来的名一样,才能完成参数的绑定。
- 若不一样,我们可以使用@RequestParam注解标明传进来参数的名称,完成参数的绑定。
二、pojo类型的绑定
Model代码:
public class User { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
表单代码:
Controller代码:
@RequestMapping("/save")public void test(User user) {}
三、数组和集合的绑定
1. 数组的绑定
表单代码:
@RequestMapping(value = "/echoArray") @ResponseBody public String echo(String[] name){ return Arrays.toString(name); }
2. List的绑定
SpringMVC不支持直接使用List接收参数,使用时,需封装在一个pojo类中
Model代码:
public class UserVo { private ListuserList; public List getUserList() { return userList; } public void setUserList(List userList) { this.userList = userList; } }
表单代码:
Controller代码:
@RequestMapping(value = "/echoList") @ResponseBody public String echoList(UserVo userVo){ ListuserList = userVo.getUserList(); return JSON.toJSONString(userList); }
3. Set的绑定
封装在pojo中,需手动创建对象,使用时下标不能超过Set集合的大小
public class UserVo { private SetuserSet = new HashSet<>(); public UserVo() { userSet.add(new User()); userSet.add(new User()); } public Set getUserSet() { return userSet; } public void setUserSet(Set userSet) { this.userSet = userSet; }}
表单代码:
Controller代码:
@RequestMapping(value = "/echoSet")@ResponseBodypublic String echoSet(UserVo userVo){ SetuserSet = userVo.getUserSet(); return JSON.toJSONString(userSet);}
4. Map的绑定
封装在pojo中
public class UserVo { private MapuserMap; public Map getUserMap() { return userMap; } public void setUserMap(Map userMap) { this.userMap = userMap; }}
表单代码:
Controller代码:
@RequestMapping(value = "/echoMap")@ResponseBodypublic String echoMap(UserVo userVo){ MapuserMap = userVo.getUserMap(); return JSON.toJSONString(userMap);}
四、json参数绑定
前台
$.ajax({ type: "POST", contentType: "application/json", dataType: "json", url: "/dataAnalysis/selsPoverty", data: JSON.stringify({ 'name': "张三", 'age': 21 }) , success: function (data) { } });
后台
@RequestMapping(value = "/echoJson")@ResponseBodypublic String echoJson(@RequestBody Mapuser){ return JSON.toJSONString(user);}