当前位置: 首页 > 教程 > Struts2 >

Struts2 <s:checkbox>复选框例子

精华
小牛编辑
132浏览
2023-03-14

创建一个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.yiibai.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.yiibai.common.action.CheckBoxAction" method="display">
	<result name="none">/pages/checkBox.jsp</result>
   </action>
		
   <action name="resultAction" class="com.yiibai.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


参考

  1. Struts2 复选框文档