这里创建一个web工程:struts2checkboxlist,来演示在多个复选框如何设置的默认值,整个项目的结构如下图所示:
在struts2,可以使用<s:checkboxlist>标签来使用相同的名称来创建多个复选框。唯一的问题是如何把握变量中的多个检查值? 例如,
public list<string> getcolors() { colors = new arraylist<string>(); colors.add("red"); colors.add("yellow"); colors.add("blue"); colors.add("green"); return colors; }
<s:checkboxlist label="what's your favor color" list="colors" name="yourcolor" value="defaultcolor" />
一个多复选框以“红”,“黄”,“蓝”和“绿色”为选项。如果有多个选项被选中,可以通过一个string对象存储。
例如,如果“红”“黄”选项被选中,选中的值将用逗号相结合连接,yourcolor = “red,yellow”.
private string yourcolor; public void setyourcolor(string yourcolor) { this.yourcolor = yourcolor; }
一个完整的struts2实例,通过<s:checkboxlist>用相同的名称创建多个复选框,存储检选中的值,并在另一页面中显示。
action类来生成和保持的多个复选框值。
checkboxlistaction.java
package com.h3.common.action; import java.util.arraylist; import java.util.list; import com.opensymphony.xwork2.actionsupport; public class checkboxlistaction extends actionsupport{ private list<string> colors; private string yourcolor; public string getyourcolor() { return yourcolor; } public void setyourcolor(string yourcolor) { this.yourcolor = yourcolor; } public checkboxlistaction(){ colors = new arraylist<string>(); colors.add("red"); colors.add("yellow"); colors.add("blue"); colors.add("green"); } public string[] getdefaultcolor(){ return new string [] {"red", "green"}; } public list<string> getcolors() { return colors; } public void setcolors(list<string> colors) { this.colors = colors; } public string execute() { return success; } public string display() { return none; } }
通过“s:checkboxlist”标签渲染多个复选框。
checkboxlist.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> </head> <body> <h1>struts 2 multiple check boxes example</h1> <s:form action="resultaction" namespace="/"> <h2> <s:checkboxlist label="what's your favor color" list="colors" name="yourcolor" value="defaultcolor" /> </h2> <s:submit value="submit" name="submit" /> </s:form> </body> </html>
result.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <body> <h1>struts 2 multiple check boxes example</h1> <h2> favor colors : <s:property value="yourcolor"/> </h2> </body> </html>
<?xml version="1.0" encoding="utf-8" ?> <!doctype struts public "-//apache software foundation//dtd struts configuration 2.0//en" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devmode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <action name="checkboxlistaction" class="com.h3.common.action.checkboxlistaction" method="display"> <result name="none">/pages/checkboxlist.jsp</result> </action> <action name="resultaction" class="com.h3.common.action.checkboxlistaction"> <result name="success">/pages/result.jsp</result> </action> </package> </struts>
http://localhost:8080/struts2checkboxlist/checkboxlistaction.action
http://localhost:8080/struts2checkboxlist/resultaction.action