创建一个web工程,它的工程名称为:struts2chechbox,其完整的项目工程结构如下:
在struts2,可以使用<s:checkbox>标签来创建一个html复选框。fieldvalue=”true”是将要提交的复选框的实际值。
<s:checkbox name="checkme" fieldvalue="true" label="check me for testing"/>
它会生成下面的html。
<input type="checkbox" name="checkme" value="true" id="xx_checkme"/> <input type="hidden" id="__checkbox_xx_checkme" name="__checkbox_checkme" value="true"/> <label for="resultaction_checkme" class="checkboxlabel">check me for testing</label>
如果想预先选择一个复选框,只需添加一个value属性,并将其设置为true。
<s:checkbox name="checkme" fieldvalue="true" value="true" label="check me for testing"/>
它会生成下面的html。
<input type="checkbox" name="checkme" value="true" checked="checked" id="xx_checkme"/> <input type="hidden" id="__checkbox_xx_checkme" name="__checkbox_checkme" value="true" /> <label for="resultaction_checkme" class="checkboxlabel">check me for testing</label>
一个完整的例子,通过struts 2中创建一个复选框<s:checkbox>, 并指派提交复选框值到action类并显示它。
action类有checkme布尔属性来保存复选框值。
checkboxaction.java
package com.h3.common.action; import com.opensymphony.xwork2.actionsupport; public class checkboxaction extends actionsupport{ private boolean checkme; public boolean ischeckme() { return checkme; } public void setcheckme(boolean checkme) { this.checkme = checkme; } public string execute() { return success; } public string display() { return none; } }
结果页面使用struts2的“s:checkbox”标签来创建一个复选框。
checkbox.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> </head> <body> <h1>struts 2 复选框示例</h1> <s:form action="resultaction" namespace="/"> <h2> <s:checkbox name="checkme" fieldvalue="true" label="check me for testing"/> </h2> <s:submit value="submit" name="submit" /> </s:form> </body> </html>
result.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <body> <h1>struts 2 复选框示例</h1> <h2> checkbox (checkme) value : <s:property value="checkme"/> </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="checkboxaction" class="com.h3.common.action.checkboxaction" method="display"> <result name="none">/pages/checkbox.jsp</result> </action> <action name="resultaction" class="com.h3.common.action.checkboxaction"> <result name="success">/pages/result.jsp</result> </action> </package> </struts>
http://localhost:8080/struts2checkbox/checkboxaction.action
http://localhost:8080/struts2checkbox/resultaction.action