第08講 struts2處理數目不定的JavaBean物件
阿新 • • 發佈:2018-11-10
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"
<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"
<td><input type="text" name="students[0].sex"/>td>
<td><input type="text" name="students[0].age"
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,測試