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之間的分隔符。這裏用的是一個空格。結果頁面如下所示: