創建一個Web工程,它的工程名稱為:struts2chechbox,其完整的專案工程結構如下:
在Struts2,可以使用<s:checkbox>標籤來創建一個HTML複選框。fieldValue=”true”是將要提交的複選框的實際值。
<s:checkbox name="checkMe" fieldValue="true" label="Check Me for testing"/>
一般情況下,不需要聲明fieldValue=“true”,因為true是默認值。
它會生成下麵的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>
Struts2 <s:checkbox> 示例
一個完整的例子,通過Struts 2中創建一個複選框<s:checkbox>, 並指派提交複選框值到Action類並顯示它。
1. 動作 - Action
Action類有checkMe布爾屬性來保存複選框值。
CheckBoxAction.java
package com.xuhuhu.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;
}
}
2. 結果頁面
結果頁面使用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>
3. struts.xml
<?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.xuhuhu.common.action.CheckBoxAction" method="display">
<result name="none">/pages/checkBox.jsp</result>
</action>
<action name="resultAction" class="com.xuhuhu.common.action.CheckBoxAction">
<result name="success">/pages/result.jsp</result>
</action>
</package>
</struts>
5. 示例
http://localhost:8080/struts2checkbox/checkBoxAction.action

http://localhost:8080/struts2checkbox/resultAction.action

參考
上一篇:
Struts2單選預選按鈕值
下一篇:
Struts2設置多個複選框缺省值
