本文主要是介绍第08讲 struts2处理数目不定的JavaBean对象,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1,在HeadFirstStruts2chapter02-02中, 导入addstudents.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 heretitle>
head>
<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>
html>
2,新建com.cruise.model包, 然后导入Student.java实体bean,
package com.cruise.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 + "]";
}
}
3,新建StudentAction.java 实现Action接口。增加的list集合,便利前台的数据。注意:这里的students集合一定要和addstudents.jsp中的students[0].name一直。
package com.cruise.action;
import java.util.List;
import com.cruise.model.Student;
import com.opensymphony.xwork2.Action;
public class StudentAction implements Action{
private List<Student> students ;
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
@Override
public String execute() throws Exception {
if (students!=null) {
for(Student stu :students){
System.out.println(stu);
}
}
return "success";
}
}
4,修改struts.xml中的action,
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>
<package name="suibiandingyi" extends="struts-default">
<action name="hobby" class="com.cruise.action.HobbyAction">
<result name="success">success.jspresult>
action>
<action name="student" class="com.cruise.action.StudentAction">
<result name="success">success.jspresult>
action>
package>
struts>
5,测试
这篇关于第08讲 struts2处理数目不定的JavaBean对象的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!