1、 处理多个基本数据类型的输入值
需要在action中创建数组,Struts2会自动填充,实现代码如下
package com.java1234.action;
import com.opensymphony.xwork2.ActionSupport;
public class HobbyAction extends ActionSupport{
private String[] hobby;
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
@Override
public String execute() throws Exception {
System.out.println("执行了Action的默认方法");
if(hobby!=null){
for(String h:hobby){
System.out.println(h);
}
}
return SUCCESS;
}
}
而前台的jsp页面为
<body>
<form action="hobby" method="post">
爱好:
<input type="checkbox" name="hobby" value="唱歌"/>唱歌
<input type="checkbox" name="hobby" value="跳舞"/>跳舞
<input type="checkbox" name="hobby" value="睡觉"/>睡觉
<input type="checkbox" name="hobby" value="玩CF"/>玩CF
<input type="submit" value="提交"/>
</form>
</body>
struts.xml中添加
<action name="hobby" class="com.java1234.action.HobbyAction">
<result name="success">success.jsp</result>
<result name="error">error.jsp</result>
</action>
运行结果
浏览器,点提交
控制台
2、处理多个对象数据类型的输入值
在action中创建对象的list集合,然后Struts2会自动填充
实现代码如下,先准备一个Student类
package com.java1234.model;
public class Student {
private String name;
private String sex;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", sex=" + sex + ", age=" + age + "]";
}
}
action类
package com.java1234.action;
import java.util.List;
import com.java1234.model.Student;
import com.opensymphony.xwork2.ActionSupport;
public class StudentAction implements Action{
private List<Student> students;
public List<Student> getStudent() {
return students;
}
public void setStudent(List<Student> students) {
this.students = students;
}
@Override
public String execute() throws Exception {
System.out.println("执行了Action的默认方法");
for(Student s:students){
System.out.println(s);
}
return SUCCESS;
}
}
前台 jsp
<body>
<form action="student" method="post">
<table>
<tr>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
</tr>
<tr>
<td><input type="text" name="students[0].name"/></td>
<td><input type="text" name="students[0].sex"/></td>
<td><input type="text" name="students[0].age"/></td>
</tr>
<tr>
<td><input type="text" name="students[1].name"/></td>
<td><input type="text" name="students[1].sex"/></td>
<td><input type="text" name="students[1].age"/></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="提交"/>
</td>
</tr>
</table>
</form>
</body>
在struts.xml中添加
<action name="student" class="com.java1234.action.StudentAction">
<result name="success">success.jsp</result>
<result name="error">error.jsp</result>
</action>
运行结果
浏览器
控制台