在Action中接收多选框的值,有2中方式:
1.定义一个数组
2.定义一个List
checkox.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>1.使用数组接收多选框的值</h3>
<form action="user/common!register" method="post">
爱好:<br/>
<input type="checkbox" name="habits" value="sports">运动<br/>
<input type="checkbox" name="habits" value="reading">读书<br/>
<input type="checkbox" name="habits" value="sleep">睡觉<br/>
<input type="submit" value="Register">
</form>
<h3>2.使用List接收多选框的值</h3>
<form action="user/common!register2" method="post">
爱好:<br/>
<input type="checkbox" name="habitList" value="sports">运动<br/>
<input type="checkbox" name="habitList" value="reading">读书<br/>
<input type="checkbox" name="habitList" value="sleep">睡觉<br/>
<input type="submit" value="Register">
</form>
</body>
</html>
UserAction
package com.deppon.demo.struts;
import java.util.List;
import com.deppon.demo.entity.UserEntity;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class UserAction extends ActionSupport {
private static final long serialVersionUID = 7146977447328113550L;
private String[] habits;
private List<String> habitList;
public List<String> getHabitList() {
return habitList;
}
public void setHabitList(List<String> habitList) {
this.habitList = habitList;
}
public String[] getHabits() {
return habits;
}
public void setHabits(String[] habits) {
this.habits = habits;
}
/**
* 使用数组接收多选框的值
* @return
*/
public String register() {
//如果一个都没有选的话,habits会是null
if(habits != null) {
for(String each : habits) {
System.out.println("habits-->" + each);
}
}
return "checkbox";
}
/**
* 使用List接收多选框的值
* @return
*/
public String register2() {
System.out.println("habitList->" + habitList);
return "checkbox";
}
}
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.i18n.encoding" value="utf-8"></constant>
<constant name="struts.multipart.maxSize" value="20971520"/>
<constant name="struts.devMode" value="true" />
<package name="p_user" namespace="/user" extends="struts-default">
<action name="common" class="com.deppon.demo.struts.UserAction">
<result type="redirect">/index.jsp</result>
<result name="checkbox" type="redirect">/checkbox.jsp</result>
</action>
</package>
</struts>