在struts2,可以通过<s:checkboxlist>标签创建多个复选框具有相同名称。棘手的问题是如何设置的默认值在多个复选框。例如,复选框以“红色”,“黄色”,“蓝色”,“绿色”选项的列表,并且要同时设置“红色”和“绿色”为默认选中的值。这里创建一个web工程:struts2setcheckboxes,来演示在多个复选框如何设置的默认值,整个项目的结构如下图所示:
一个 <s:checkboxlist> 示例
<s:checkboxlist label="what's your favor color" list="colors" name="yourcolor" />
产生下面的html代码
<td class="tdlabel"><label for="resultaction_yourcolor" class="label"> what's your favor color:</label> </td> <td > <input type="checkbox" name="yourcolor" value="red" id="yourcolor-1" /> <label for="yourcolor-1" class="checkboxlabel">red</label> <input type="checkbox" name="yourcolor" value="yellow" id="yourcolor-2" /> <label for="yourcolor-2" class="checkboxlabel">yellow</label> <input type="checkbox" name="yourcolor" value="blue" id="yourcolor-3" /> <label for="yourcolor-3" class="checkboxlabel">blue</label> <input type="checkbox" name="yourcolor" value="green" id="yourcolor-4" /> <label for="yourcolor-4" class="checkboxlabel">green</label> <input type="hidden" id="__multiselect_resultaction_yourcolor" name="__multiselect_yourcolor" value="" /> </td>
action类提供颜色选项的复选框的列表。
//... public class checkboxlistaction extends actionsupport{ private list<string> colors; private string yourcolor; public checkboxlistaction(){ colors = new arraylist<string>(); colors.add("red"); colors.add("yellow"); colors.add("blue"); colors.add("green"); } public list<string> getcolors() { return colors; } //... }
要作为默认选中的值设为“红”选项,只是在行动类中添加一个方法,并返回一个“red”的值。
//... public class checkboxlistaction extends actionsupport{ //add a new method public string getdefaultcolor(){ return "red"; } }
在<s:checkboxlist>标签中,添加一个value属性并指向 getdefaultcolor()方法。
<s:checkboxlist label="what's your favor color" list="colors" name="yourcolor" value="defaultcolor" />
再次运行它,“红”选项将被默认选中。
要设置多个值“红色”和“绿色”作为默认选中的值,就返回一个“string []”,而不是“string ”,在struts 2将相应匹配。
//... public class checkboxlistaction extends actionsupport{ //now return a string[] public string[] getdefaultcolor(){ return new string [] {"red", "green"}; } }
<s:checkboxlist label="what's your favor color" list="colors" name="yourcolor" value="defaultcolor" />
再次运行它,“红色”和“绿色”的选项将被默认选中。
http://localhost:8080/struts2setcheckboxes/checkboxlistaction.action
点击提交后,显示结果如下图所示: