看到Spring+MyBatis企业应用实战(第二版)的Spring MVC的标签库一节时,有如下疑惑:checkboxes示例代码的最后一条和select+options示例代码的最后一条好像不太一样,checkboxes中employee.depts是个Dept对象的List,而select+options中user.deptId只是Dept对象中的id而已(是不是List其实不重要,关键在于这里直接用id匹配了Dept对象)。
Spring MVC中的checkboxes,radiobuttons和selects可以方便的把List,Set和Map对象的field映射到html文档中的选项标签中,同时可以提供default选项。但是有一个细节需要注意,以checkboxes为例,下面的代码是可以正确运行的:
<form:form modelAttribute="user" method="post" action="selectForm" >
<table>
<tr>
<td>兴趣:</td>
<td>
<form:checkboxes path="hobbies" items="${hobbyList}"
itemLabel="name" itemValue="id"/>
</td>
</tr>
</table>
</form:form>
@GetMapping(value="/selectForm4")
public String selectForm4(Model model) {
User user = new User();
List<Hobby> l = new ArrayList<>();
Hobby animation = new Hobby(1, "动漫");
Hobby computerGame = new Hobby(2, "游戏");
Hobby sports = new Hobby(3, "运动");
Hobby singing = new Hobby(4, "唱歌");
l.add(animation);
l.add(computerGame);
user.setHobbies(l);
List<Hobby> hobbyList = new ArrayList<>();
hobbyList.add(animation);
hobbyList.add(computerGame);
hobbyList.add(sports);
hobbyList.add(singing);
model.addAttribute("user", user);
model.addAttribute("hobbyList", hobbyList);
return "selectForm";
}
但下面这个不可以:
@GetMapping(value="/selectForm4")
public String selectForm4(Model model) {
User user = new User();
List<Hobby> l = new ArrayList<>();
l.add(new Hobby(1, "动漫"));
l.add(new Hobby(2, "游戏"));
user.setHobbies(l);
List<Hobby> hobbyList = new ArrayList<>();
hobbyList.add(new Hobby(1, "动漫"));
hobbyList.add(new Hobby(2, "游戏"));
hobbyList.add(new Hobby(3, "运动"));
hobbyList.add(new Hobby(4, "唱歌"));
model.addAttribute("user", user);
model.addAttribute("hobbyList", hobbyList);
return "selectForm";
}
区别在于,后面这个代码为CheckBox准备的选项列表hobbyList中的对象和default选项user.hobbies中的对象虽然“值”可以对应上,但其实不是同一个对象。可见在最终解析的时候是比较引用而不是比较值的。
另外一个方法可以只摄者default选项的value:
<form:form modelAttribute="user" method="post" action="selectForm" >
<table>
<tr>
<td>兴趣:</td>
<td>
<form:checkboxes path="hobbyIds" items="${hobbyList}"
itemLabel="name" itemValue="id"/>
</td>
</tr>
</table>
</form:form>
@GetMapping(value="/selectForm4")
public String selectForm4(Model model) {
User user = new User();
List<Integer> l = new ArrayList<>();
l.add(1);
l.add(2);
user.setHobbyIds(l);
List<Hobby> hobbyList = new ArrayList<>();
hobbyList.add(new Hobby(1, "动漫"));
hobbyList.add(new Hobby(2, "游戏"));
hobbyList.add(new Hobby(3, "运动"));
hobbyList.add(new Hobby(4, "唱歌"));
model.addAttribute("user", user);
model.addAttribute("hobbyList", hobbyList);
return "selectForm";
}
综上,checkboxes,radiobuttons和selects等Spring MVC中备选项和default选项之间的匹配存在两种匹配模式:按对象引用匹配和按value匹配。