1.6 radiobutton标签
radiobutton标签会被渲染为一个type为radio的普通HTML input标签。radiobutton标签也是可以绑定数据的。以下是一个radiobutton的简单应用示例:
- <form:form action="formTag/form.do" method="post" commandName="user">
- <table>
- <tr>
- <td>性别:</td>
- <td>
- <form:radiobutton path="sex" value="1"/>男
- <form:radiobutton path="sex" value="0"/>女
- </td>
- </tr>
- <tr>
- <td colspan="2"><input type="submit" value="提交"/></td>
- </tr>
- </table>
- </form:form>
<form:form action="formTag/form.do" method="post" commandName="user">
<table>
<tr>
<td>性别:</td>
<td>
<form:radiobutton path="sex" value="1"/>男
<form:radiobutton path="sex" value="0"/>女
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="提交"/></td>
</tr>
</table>
</form:form>
在上面代码中我们的radiobutton标签都是绑定了表单对象user的sex属性,当sex为1的时候就代表性别为男,上面性别为男的那一行就会被选中,当sex为0的时候就代表性别为女,上面性别为女的那一行就会被选中。
1.7 radiobuttons标签
radiobuttons标签跟radiobutton标签的区别如同checkbox标签对checkboxes标签的区别。使用radiobuttons标签的时候将生成多个单选按钮。使用radiobuttons有两个属性也是我们必须指定的,一个是path属性,表示绑定的表单对象对应的属性,另一个是items属性,表示用于生成单选按钮的数据源。跟checkboxes一样,radiobuttons的items属性和path属性都可以是Array、集合或者是Map。现在我们假设user在篮球、足球、乒乓球、羽毛球和排球这5种运动中选择一种作为自己最喜欢的球类运动。处理器方法和返回的对应的视图代码如下:
- @RequestMapping(value="form", method=RequestMethod.GET)
- public String formTag(Map<String, Object> map) {
- User user = new User();
- user.setFavoriteBall(4);//设置我最喜爱的球类运动是4羽毛球
- Map<Integer, String> ballMap = new HashMap<Integer, String>();
- ballMap.put(1, "篮球");
- ballMap.put(2, "足球");
- ballMap.put(3, "乒乓球");
- ballMap.put(4, "羽毛球");
- ballMap.put(5, "排球");
- map.put("user", user);
- map.put("ballMap", ballMap);
- return"formTag/form";
- }
@RequestMapping(value="form", method=RequestMethod.GET)
public String formTag(Map<String, Object> map) {
User user = new User();
user.setFavoriteBall(4);//设置我最喜爱的球类运动是4羽毛球
Map<Integer, String> ballMap = new HashMap<Integer, String>();
ballMap.put(1, "篮球");
ballMap.put(2, "足球");
ballMap.put(3, "乒乓球");
ballMap.put(4, "羽毛球");
ballMap.put(5, "排球");
map.put("user", user);
map.put("ballMap", ballMap);
return "formTag/form";
}
- <form:form action="formTag/form.do" method="post" commandName="user">
- <table>
- <tr>
- <td>最喜欢的球类:</td>
- <td>
- <form:radiobuttons path="favoriteBall" items="${ballMap}" delimiter=" "/>
- </td>
- </tr>
- <tr>
- <td colspan="2"><input type="submit" value="提交"/></td>
- </tr>
- </table>
- </form:form>
<form:form action="formTag/form.do" method="post" commandName="user">
<table>
<tr>
<td>最喜欢的球类:</td>
<td>
<form:radiobuttons path="favoriteBall" items="${ballMap}" delimiter=" "/>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="提交"/></td>
</tr>
</table>
</form:form>
在上述代码中我们可以看到我们使用了radiobuttons的delimiter属性,该属性表示进行展示的radiobutton之间的分隔符。这里用的是一个空格。结果页面如下所示: