定义
百度百科定义:
简单绑定是将一个用户界面元素(控件)的属性绑定到一个类型(对象)实例上的某个属性的方法。
例如,如果一个开发者有一个Customer类型的实例,那么他就可以把Customer的“Name”属性绑定到一个TextBox的“Text”属性上。“绑定”了这2个属性之后,对TextBox的Text属性的更改将“传播”到Customer的Name属性,而对Customer的Name属性的更改同样会“传播”到TextBox的Text属性。
支持的数据绑定方式
SpringMVC的各种参数包括对象java对象,集合,Map以及基本数据类型的绑定方式
1.基本类型,包装类型的绑定
1.1基本数据类型的绑定
基本类型的数据绑定需要注意的是:后台请求方法中声明的参数前台是必须传的,其次是类型必须相同
controller类:
@Controllerpublic class DataBind {// http://localhost:8080/dataBind/test.do?age=11 @RequestMapping("/test") public String test(int age){ System.out.println(age); return "success"; } }
form表单
<form action="test.do" method="post"> <input name="age" value="11" type="text"/> ...... </form>
注意:
1.参数名一致:表单中input的name值和Controller的参数变量名保持一致 ,就能完成基本数据类型的数据绑定.
2.参数类型一致:如果在后台参数定义的是int类型,那么前台传的值也只能是int类型否则springMVC会进行拦截报一个400参数错误(数据转换的异常) 3.参数不能为空:从jsp提交过来的数据为null或者""的话,会出现500异常。也就是说,必须保证表单传递过来的数据不能为null或"".
对于以上问题可以采用@RequestParam注解来解决
@Controllerpublic class DataBind { // @RequestMapping("/test") public String test(@RequestParam(value ="age" ,required = false) int userAge){ System.out.println(userAge); return "success"; } }
@RequestParam(value ="name" ,required = false) value值是参数别名与表单一致,required 默认值true为必传.
1.2包装类型的绑定
controller类:
@RequestMapping("/test3") public String test3(Integer age){ System.out.println(age); }
form表单:
<form action="test.do" method="post"> <input name="age" value="10" type="text"/> ...... </form>
和基本数据类型基本一样,不同之处在于,JSP表单传递过来的数据可以为null或"",以上面代码为例,如果jsp中num为""或者表单中无age这个input,那么,Controller方法参数中的num值则为null。
2.简单对象,复杂对象的绑定
2.1简单对象&多层对象
1. 简单POJO类对象:
public class User { private String firstName; private String lastName; //省略get&set ... }
controller类
@RequestMapping("/test4") public String test4(User user){ System.out.println(user); return "success"; }
form表单
<form action="test.do" method="post"> <input name="firstName" value="张" type="text"/> <input name="lastName" value="三" type="text"/> ...... </form>
简单对象:请求方式的参数Key即为对象属性名,不用加“对象名.”的前缀
2.多层对象
POJO对象
public class ContactInfo { private String tel; private String address; //。。。省略get&set } public class User { private String firstName; private String lastName; private ContactInfo contactInfo; // 。。。 省略get&set
controller类和简单对象没有什么区别,参数类型都是User(pojo类型对象)
form表单
<form action="<%=basePath%>test5.do" method="get"> 姓:<input name="firstName"/> 名:<input name="lastName"/> 地址:<input name="contactInfo.address"/>...</form>
多层级对象:第二级以上对象必须加“对象名.”的前缀。
2.2.同属性的多对象
<pre class="hljs css" style="box-sizing: inherit; -webkit-tap-highlight-color: transparent; user-select: text !important; display: block; overflow-x: auto; padding: 2px; background: rgb(63, 63, 63); color: rgb(220, 220, 220); border-radius: 3px; line-height: 1.4; word-wrap: normal; font-size: 13px; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">同属性的多对象 在control中声明@initBinder的WebDataBinder的前缀</pre>
当两个对象含有相同属性时,为了精确的匹配绑定一种方法是通过命名的规范去规避,另一中解决办法使用@InitBinder对请求参数加前缀
java代码
@Controller public class dataBind{ @InitBinder("teacher") public void initBinder1(WebDataBinder binder){ binder.setFieldDefaultPrefix("teacher."); } @InitBinder("student") public void initBinder2(WebDataBinder binder){ binder.setFieldDefaultPrefix("student."); } //URL映射 @RequestMapping(value="/save", method = RequestMethod.GET) public ModelAndView save(Teacher teacher,Student student) { System.out.println(teacher.getName()+" "+student.getName()); return null; }
注意:当save的参数名与对象名不一致(即参数名不为类名的小写)时,需要在参数前加@ModelAttribute()注解,同时保证@InitBinder的value值与@ModelAttribute的value值一致,如果不指定value值,那么所有的都将使用。
这种方式的缺点:
1、不支持Path variable的绑定,如/test1/{user1.id}这种情况的绑定;
2、不支持如集合/数组的绑定;
@InitBinder("user1") public void initUser(WebDataBinder binder){ binder.setFieldDefaultPrefix("user."); } @InitBinder("student1") public void initStudent(WebDataBinder binder){ binder.setFieldDefaultPrefix("student."); } @RequestMapping("/test6") public String test6(@ModelAttribute("student1")Student a,@ModelAttribute("user1")User b){ System.out.println(a); System.out.println(b); return "success"; }
3.List,Set,Map类型的数据绑定
3.1 List类型的数据绑定
springMVC 不支持list类型的直接转换,需包装成object。
public class User { private String firstName; private String lastName; // 。。。 省略get&set } public class UserListForm { private List<User> users; // 。。。 省略get&set}
@RequestMapping("test") public void test(UserListForm userForm) { for (User user : userForm.getUsers()) { System.out.println(user.getFirstName() + " - " + user.getLastName()); } }
form表单
<form action="test.do" method="post"> <table> <thead> <tr> <th>First Name</th> <th>Last Name</th> </tr> </thead> <tfoot> <tr> <td colspan="2"><input type="submit" value="Save" /></td> </tr> </tfoot> <tbody> <tr> <td><input name="users[0].firstName" value="aaa" /></td> <td><input name="users[0].lastName" value="bbb" /></td> </tr> <tr> <td><input name="users[1].firstName" value="ccc" /></td> <td><input name="users[1].lastName" value="ddd" /></td> </tr> <tr> <td><input name="users[2].firstName" value="eee" /></td> <td><input name="users[2].lastName" value="fff" /></td> </tr> </tbody> </table> </form>
这里的UserListForm对象里面的属性被定义成List,而不是普通自定义对象。所以,在JSP中需要指定List的下标。值得一提的是,Spring会创建一个以最大下标值为size的List对象,所以,如果JSP表单中有动态添加行、删除行的情况,就需要特别注意,譬如一个表格,用户在使用过程中经过多次删除行、增加行的操作之后,下标值就会与实际大小不一致,这时候,List中的对象,只有在jsp表单中对应有下标的那些才会有值,否则会为null.
<pre class="hljs cpp" style="box-sizing: inherit; -webkit-tap-highlight-color: transparent; user-select: text !important; display: block; overflow-x: auto; padding: 2px; background: rgb(63, 63, 63); color: rgb(220, 220, 220); border-radius: 3px; line-height: 1.4; word-wrap: normal; font-size: 13px; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">list集合绑定的时候 下标最好是连续的 否则可能造成后台资源浪费</pre>
3.2 Set类型的数据绑定
Set和List类似,也需要绑定在对象上,而不能直接写在Controller方法的参数中。但是,绑定Set数据时,必须先在Set对象中add相应的数量的,即Set绑定时需初始化
public class User { private String firstName; private String lastName; //...省略set&get } public class UserSetForm { private Set<User> users = new HashSet<User>(); public UserSetForm(){ users.add(new User()); users.add(new User()); users.add(new User()); } //...省略set&get }
本文原創發布于慕課網 ,轉載請注明出處,謝謝合作
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
Kindle 閱讀器、小米平衡車
Apple iPad (10.2英寸)、大額優惠券
在等著你去兌換了噢
無門檻使用