2009年7月26日 星期日

Struts2 + MySql實現分頁顯示之CRUD功能

 一般在製作Web應用程式時,經常會用到分頁顯示的功能,在此利用Struts2 + Mysql資料庫實作分頁顯示之CRUD(Create,Read,Update,Delete)功能。
使用工具:JDK 1.5+Eclipse 3.4+Tomcat 6.0.14+Struts 2.0.11+MySql 5.1.36
實作步驟如下:
1.建立一個Dynamic Web Project並將Struts2及MySql connection jar放到WEB-INF\lib目錄下
2.修改web.xml,此檔案放置於WEB-INF目錄下,檔案內容如下:
<?Xml version="1.0" encoding="utf-8"?>
<Web-app xmlns:xsi="http://www.W3.Org/2001/xmlschema-instance"
xmlns="http://java.Sun.Com/xml/ns/javaee"
xmlns:web="http://java.Sun.Com/xml/ns/javaee/web-app_2_5.Xsd"
xsi:schemalocation="http://java.Sun.Com/xml/ns/javaee
http://java.Sun.Com/xml/ns/javaee/web-app_2_5.Xsd"
id="webapp_id" version="2.5">
<display-name>study</display-name>
<!-- For struts2 start -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.Apache.Struts2.Dispatcher.Filterdispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- For struts2 end -->
<welcome-file-list>
<welcome-file>index.Html</welcome-file>
<welcome-file>index.Htm</welcome-file>
<welcome-file>index.Jsp</welcome-file>
</welcome-file-list>
</web-app>
3.建立一個表格,用於儲存學員資料,Sql Script如下:

drop database if exists manning;
create database manning;
use manning
create table student (
stu_id integer auto_increment,
stuName varchar(255) not null,
address varchar(255) not null,
stuPhone varchar(255)not null,
primary key(stu_id)
);

insert into student(stuName,address,stuPhone) values('楊華林','長沙','13787825190');
insert into student(stuName,address,stuPhone) values('李明清','天津','13787525190');
insert into student(stuName,address,stuPhone) values('李小華','大連','13788451190');
insert into student(stuName,address,stuPhone) values('鄭小明','蘇州','13787052188');
insert into student(stuName,address,stuPhone) values('楊一新','西安','13787851190');
insert into student(stuName,address,stuPhone) values('王新任','廣州','13787056460');
insert into student(stuName,address,stuPhone) values('謝小華','深圳','13787075550');
insert into student(stuName,address,stuPhone) values('王建明','廈門','13788853690');
insert into student(stuName,address,stuPhone) values('秦一生','北京','13788689236');
insert into student(stuName,address,stuPhone) values('田翠林','杭州','13787655150');
insert into student(stuName,address,stuPhone) values('陳小明','廣州','13787623668');
4.建立資料庫連線類別DataAccess.java:類別內容如下:

package study;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class DataAccess {
private Connection conn;
private DataSource ds;
private static final String driver="com.mysql.jdbc.Driver";
private static final String url="jdbc:mysql://localhost:3306/manning";
private static final String username="manning";
private static final String password="action";
public Connection getConnection()throws Exception{
try{
Class.forName(driver);
conn =  DriverManager.getConnection(url,username,password);
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
throw new Exception(cnfe.getMessage());
}catch(SQLException sqle){
sqle.printStackTrace();
throw new Exception(sqle.getMessage());
}
return conn;
}
public Connection getConnectionPool()throws Exception{
try{
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
ds = (DataSource)envContext.lookup("jdbc/manningDB");
}catch(NamingException ne){
ne.printStackTrace();
throw new Exception(ne.getMessage());
}
try{
conn = ds.getConnection();
}catch(SQLException sqle){
sqle.printStackTrace();
throw new Exception(sqle.getMessage());
}
return conn;
}
}
5.建立一個類別Student.java,當作Java Bean類別內容如下:
package study;

public class Student {
private int stu_id;
private String stuName;
private String address;
private String stuPhone;

public Student(){

}

public int getStu_id(){
return stu_id;
}
public void setStu_id(int stu_id){
this.stu_id=stu_id;
}
public String getStuName(){
return stuName;
}
public void setStuName(String stuName){
this.stuName = stuName;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address=address;
}
public String getStuPhone(){
return stuPhone;
}
public void setStuPhone(String stuPhone){
this.stuPhone=stuPhone;
}
}
6.建立分頁功能類別PageDAO.java及StudentDAO.java,類別內容分別如下:
package study;

import java.util.List;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PageDAO{
 private Connection conn;
 private PreparedStatement pstmt;
 private ResultSet rs;
 private DataAccess da = new DataAccess();
 private Student student;
 public List<Student> queryByPage(int pageSize,int pageNow)throws Exception{
  List<Student> list = new ArrayList<Student>();
  String sql=null;
  if(conn==null){
   //conn = da.getConnection();
   conn = da.getConnectionPool();
  } 
  try{  
   if(conn!=null && pageSize>0 && pageNow>0){
    sql = "select * from student order by stu_id limit ";
    sql = sql+(pageNow*pageSize-pageSize)+","+pageSize;
    pstmt = conn.prepareStatement(sql);
    rs = pstmt.executeQuery();
    while(rs.next()){
     student = new Student();
     student.setStu_id(rs.getInt("stu_id"));
     student.setStuName(rs.getString("stuName"));
     student.setAddress(rs.getString("address"));
     student.setStuPhone(rs.getString("stuPhone"));
     list.add(student);
    }
   }
  }catch(SQLException sqle){
   sqle.printStackTrace();
   throw new Exception(sqle.getMessage());
  }finally{
   if(!conn.isClosed()){
    if(rs!=null){
     rs.close();
    }
    if(pstmt!=null){
     pstmt.close();
    }
    conn.close();
    conn=null;
   }
  }
  return list; 
 }
 public int getCount()throws Exception{
  String sql = null;
  int count = 0;
  if(conn==null){
   //conn = da.getConnection();
   conn = da.getConnectionPool();
  }
  try{
   if(conn!=null){
    sql = "select count(stu_id) as count from student";
    pstmt = conn.prepareStatement(sql);
    rs = pstmt.executeQuery();
    while(rs.next()){
     count = rs.getInt("count");
    }
   }
  }catch(SQLException sqle){
   sqle.printStackTrace();
   throw new Exception(sqle.getMessage());
  }catch(Exception e){
   e.printStackTrace();
   throw new Exception(e.getMessage());
  }finally{
   if(!conn.isClosed()){
    if(rs!=null){
     rs.close();
    }
    if(pstmt!=null){
     pstmt.close();
    }
    conn.close();
    conn=null;
   }
  }
  return count;
 }
}
==============================================================
package study;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentDAO {
 private Connection conn;
 private PreparedStatement pstmt;
 private ResultSet rs;
 private String sql;
 private DataAccess da = new DataAccess();

 public void student_Insert(String stuName,String stuPhone,String address)throws Exception{
  if(conn==null){
   conn = da.getConnectionPool();
  }
  try{
   sql="insert into student(stuName,stuPhone,address) values (?,?,?)";
   pstmt = conn.prepareStatement(sql);
   pstmt.setString(1, stuName);
   pstmt.setString(2, stuPhone);
   pstmt.setString(3, address);
   pstmt.execute();
  }catch(SQLException sqle){
   sqle.printStackTrace();
   throw new Exception(sqle.getMessage());
  }finally{
   if(!conn.isClosed()){
    if(pstmt!=null){
     pstmt.close();
    }
    conn.close();
    conn=null;
   }
  }
 }

 public void student_Update(String stuName,String stuPhone,String address,int stu_id)throws Exception{
  if(conn==null){
   conn = da.getConnectionPool();
  }
  try{
   sql = "update student set stuName=?,stuPhone=?,address=? where stu_id=?";
   pstmt = conn.prepareStatement(sql);
   pstmt.setString(1, stuName);
   pstmt.setString(2, stuPhone);
   pstmt.setString(3, address);
   pstmt.setInt(4, stu_id);  
   pstmt.executeUpdate();
  }catch(SQLException sqle){
   sqle.printStackTrace();
   throw new Exception(sqle.getMessage());
  }finally{
   if(!conn.isClosed()){
    if(pstmt!=null){
     pstmt.close();
    }
    conn.close();
    conn=null;
   }
  }
 }

 public void student_Delete(int stu_id)throws Exception{
  if(conn==null){
   conn = da.getConnectionPool();
  }
  try{
   sql="delete from student where stu_id=?";
   pstmt = conn.prepareStatement(sql);
   pstmt.setInt(1, stu_id);
   pstmt.execute();
  }catch(SQLException sqle){
   sqle.printStackTrace();
   throw new Exception(sqle.getMessage());
  }finally{
   if(!conn.isClosed()){
    if(pstmt!=null){
     pstmt.close();
    }
    conn.close();
    conn=null;
   }
  } 
 }
}
===============================================================

7.編輯jsp網頁:index.jsp,Error.jsp,show.jsp,showDetail.jsp,updateForm.jsp,updateSuccess.jsp,insertForm.jsp,insertSuccess.jsp,deleteSuccess.jsp
index.jsp:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Struts2:實現JSP分頁</title>
</head>
<body>
<div align="justify">
<ul>
<li><a href="<s:url action='show.action' />">查看學員列表</a></li>
<li><a href="<s:url action='insertForm.action' />">新增學員基本資料</a></li>
</ul>
<s:debug/>
</div>
</body>
</html>
===========================================
Error.jsp:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Error page</title>
</head>
<body>
<s:debug/>
<h4>This application has malfunctioned.</h4>
<p>  Please read through the following detailed account of the
problems encounted during the processing of your request.  After determining what mistakes you
may have made, please resubmit your request.  Better luck next time! </p>

<p><h4>Exception Name: </h4><font color="red"><s:property value="exception" /></font></p>
<p><h4>What you did wrong:</h4><font color="red"><s:property value="exceptionStack" /></font></p>

<h5>Also, please confirm that your Internet is working before actually contacting us.</h5>
</body>
</html>
==========================================
show.jsp:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>分頁秀出學員資料</title>
</head>
<script type="text/javascript">
var i=0;
function ProcessTimer(){
setInterval("showTimer()",1000);
}
function showTimer(){
i++;
msg.innerText=i;
var date = new Date();
dateTime.innerText=date.getMonth()+1+"/"+date.getDate()+"/"+date.getYear()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
}
</script>
<body onload="ProcessTimer()">
<div align="center">
<h3>學生連絡資料</h3>
<table border="1" bordercolor="#999999">
<tr bgcolor="#CCFFFF">
<th>學號</th>
<th>姓名</th>
<th>地址</th>
<th>電話</th>
<th colspan=3>動作</th>
</tr>
<s:iterator value="students" status="status">
<s:if test="#status.odd==true">
<tr bgcolor="pink">
</s:if>
<s:else>
<tr bgcolor="#FF99FF">
</s:else>
<td><s:property value="stu_id" /></td>
<td><s:property value="stuName" /></td>
<td><s:property value="address" /></td>
<td><s:property value="stuPhone" /></td>
<script type="text/javascript">
function edit_<s:property value='#status.index' />(){
location.href="updateForm.action?sid=<s:property value='#status.index'/>&pageNow=<s:property value='pageNow'/>";
}
function delete_<s:property value='#status.index' />(){
location.href="delete.action?sid=<s:property value='#status.index'/>";
}
function showDetail_<s:property value='#status.index' />(){
location.href="showDetail.action?sid=<s:property value='#status.index'/>&pageNow=<s:property value='pageNow'/>";
}
</script>
<td><input type="button" value="編輯" onclick="edit_<s:property value='#status.index' />()"/>
<td><input type="button" value="刪除" onclick="delete_<s:property value='#status.index' />()"/>
<td><input type="button" value="查看" onclick="showDetail_<s:property value='#status.index' />()"/>
</tr>
</s:iterator>
<!-- put students to session -->
<s:set name="students" value="students" scope="session"></s:set>
</table>
<br/>
<s:url id="url_pre" value="show.action">
<s:param name="pageNow" value="pageNow-1"></s:param>
</s:url>
<s:url id="url_next" value="show.action">
<s:param name="pageNow" value="pageNow+1"></s:param>
</s:url>
<s:url id="url_last" value="show.action">
<s:param name="pageNow" value="totalPage"></s:param>
</s:url>
<s:url id="url_first" value="show.action">
<s:param name="pageNow" value="1"></s:param>
</s:url>
<script type="text/javascript">
function nextPage(){
location.href="<s:property value='#url_next'/>";
}
function prePage(){
location.href="<s:property value='#url_pre'/>";
}
function lastPage(){
location.href="<s:property value='#url_last'/>";
}
function firstPage(){
location.href="<s:property value='#url_first'/>";
}
</script>
<s:if test="students.size()==0"/>
<s:elseif test="%{pageNow==1}">
<!--
<s:a href="#url_next">下一頁</s:a>&nbsp;&nbsp;&nbsp;&nbsp;
<s:a href="#url_last">最後一頁</s:a><br/><br/>
-->
<input type="button" value="下一頁" onclick="nextPage()"/>&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" value="最後一頁" onclick="lastPage()"/><br/><br/>
</s:elseif>
<s:elseif test="%{totalPage==pageNow}">
<!--
<s:a href="#url_pre">上一頁</s:a>&nbsp;&nbsp;&nbsp;&nbsp;
<s:a href="#url_first">第一頁</s:a><br/><br/>
-->
<input type="button" value="上一頁" onclick="prePage()"/>&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" value="第一頁" onclick="firstPage()"/><br/><br/>
</s:elseif>
<s:else>
<!--
<s:a href="#url_pre">上一頁</s:a>&nbsp;&nbsp;&nbsp;&nbsp;
<s:a href="#url_next">下一頁</s:a>&nbsp;&nbsp;&nbsp;&nbsp;
<s:a href="#url_first">第一頁</s:a>&nbsp;&nbsp;&nbsp;&nbsp;
<s:a href="#url_last">最後一頁</s:a><br/><br/>
-->
<input type="button" value="上一頁" onclick="prePage()"/>&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" value="下一頁" onclick="nextPage()"/>&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" value="第一頁" onclick="firstPage()"/>&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" value="最後一頁" onclick="lastPage()"/><br/><br/>
</s:else>
共<s:property value="totalCount"/>筆記錄,
共<s:property value="totalPage"/>頁,
第<s:property value="pageNow"/>頁&nbsp;&nbsp;&nbsp;&nbsp;
<a href="main.action">回到首頁</a>
</div>
<br/>
<div>
Timer:<span id=msg></span><br/>
Current Date Time:<span id=dateTime></span>
<s:debug/>
</div>
</body>
</html>
============================================
shwoDetail.jsp:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Show Detail student form</title>
</head>
<% session.removeAttribute("students"); %>
<body>
<div align="center">
<table border="0">
<tr><th colspan=2>學生基本資料</th></tr>
<tr><td><s:label key="stu_id" label="學號"/></td></tr>
<tr><td><s:label key="stuName" label="姓名"/></td></tr>
<tr><td><s:label key="stuPhone" label="電話"/></td></tr>
<tr><td><s:label key="address" label="住址"/></td></tr>
</table>
<a href="show.action?pageNow=<s:property value='pageNow'/>">查看學員列表</a>&nbsp;&nbsp;<a href="main.action">回到首頁</a>
<s:debug/>
</div>
</body>
</html>
============================================
updateForm.jsp:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Update Student form</title>
</head>
<%
session.removeAttribute("students");
String pageNow = request.getParameter("pageNow");
%>
<script type="text/javascript">
function doSumit(cmd){
if(cmd=="go"){
document.myform.action="/Study/update.action?pageNow=<%=pageNow%>";
}
if(cmd=="back"){
document.myform.action="/Study/show.action?pageNow=<%=pageNow%>";
}
document.myform.submit();
}
</script>
<body>
<div align="center">
<h3>修改學生基本資料</h3>
<table>
<s:form name="myform" action="update">
<tr><td><s:textfield key="stu_id" label="學號" readonly="true"/></td></tr>
<tr><td><s:textfield key="stuName" label="姓名"/></td></tr>
<tr><td><s:textfield key="stuPhone" label="電話"/></td></tr>
<tr><td><s:textfield key="address" label="住址"/></td></tr>
<tr><td colspan=2 align="right"><input type="button" value="提交" onclick="doSumit('go');"/></td></tr>
<tr><td colspan=2 align="right"><input type="button" value="回到前頁" onclick="doSumit('back');"/></td></tr>
</s:form>
</table>
</div>
<s:debug/>
</body>
</html>
==========================================
updateSuccess.jsp:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Update student data Success</title>
</head>
<%
session.removeAttribute("students");
%>
<body>
<h3>學生:<s:property value="stuName"/>,基本資料更新完成</h3><br/>
<a href="show.action?pageNow=<s:property value='pageNow'/>">查看學員列表</a>&nbsp;&nbsp;<a href="main.action">回到首頁</a>
<s:debug/>
</body>
</html>
=========================================
insertForm.jsp:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>新增學員基本資料</title>
</head>
<body onload="insertForm.stuName.focus()">
<div align="center">
<h3>新增學員基本資料</h3>
<s:form name="insertForm" action="insert">
<s:textfield key="stuName" label="姓名" />
<s:textfield key="stuPhone" label="電話" />
<s:textfield key="address" label="住址"  />
<s:submit/>
</s:form>
<input type="button" value="上一頁" onclick="javascript:history.go(-1)">
<s:debug/>
</div>
</body>
</html>
========================================
insertSuccess.jsp:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>學員基本資料新增完成</title>
</head>
<body>
<div align="center">
<h3>學員:<s:property value="stuName"/>,基本資料新增完成</h3>
<a href="<s:url action='show.action' />">查看學員列表</a>
<a href="<s:url action='main.action' namespace='/'/>">回到首頁</a>
<s:debug/>
</div>
</body>
</html>
========================================
deleteSuccess.jsp:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>刪除學員基本資料</title>
</head>
<%
session.removeAttribute("students");
%>
<body>
<div align="center">
<h3>學員:<s:property value="stuName"/>,基本資料刪除完成</h3>
<a href="show.action">查看學員列表</a>
<a href="main.action">回到首頁</a>
<s:debug/>
</div>
</body>
</html>
=======================================
8.製作相對應之Struts2 Action
Main.java
package study;
import com.opensymphony.xwork2.ActionSupport;

public class Main extends ActionSupport {
private String stuName;
private String sid;
private String pageNow;
public String execute(){
return SUCCESS;
}
public String getStuName(){
return stuName;
}
public void setStuName(String stuName){
this.stuName=stuName;
}
public String getSid(){
return sid;
}
public void setSid(String sid){
this.sid=sid;
}
public String getPageNow(){
return pageNow;
}
public void setPageNow(String pageNow){
this.pageNow=pageNow;
}
}
===================================
ShowAction.java
package study;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;

public class ShowAction extends ActionSupport {
private List<Student> students;
private int pageNow=1;
private int pageSize=5;
private int totalCount=0;//total count for student record.
private int totalPage=0;//total page for student record.
private PageDAO pageDAO = new PageDAO();
private String sid;
private String stuName;
private String stuPhone;
private String stu_id;
private String address;

public String execute()throws Exception{
students = pageDAO.queryByPage(pageSize, pageNow);
totalCount = pageDAO.getCount();
if(totalCount%pageSize==0){
totalPage = totalCount/pageSize;
}else{
totalPage = totalCount/pageSize+1;
}
if(students==null){
return ERROR;
}
return SUCCESS;
}
public List<Student> getStudents(){
return students;
}
public void setStudents(List<Student> students){
this.students=students;
}
public int getPageNow(){
return pageNow;
}
public void setPageNow(int pageNow){
this.pageNow=pageNow;
}
public int getPageSize(){
return pageSize;
}
public void setPageSize(int pageSize){
this.pageSize=pageSize;
}
public int getTotalCount(){
return totalCount;
}
public void setToalCount(int totalCount){
this.totalCount=totalCount;
}
public int getTotalPage(){
return totalPage;
}
public void setTotalPage(int totalPage){
this.totalPage=totalPage;
}
public String getSid(){
return sid;
}
public void setSid(String sid){
this.sid=sid;
}
public String getStuName(){
return stuName;
}
public void setStuName(String stuName){
this.stuName=stuName;
}
public String getStuPhone(){
return stuPhone;
}
public void setStuPhone(String stuPhone){
this.stuPhone=stuPhone;
}
public String getStu_id(){
return stu_id;
}
public void setStu_id(String stu_id){
this.stu_id=stu_id;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address=address;
}
}
========================================
UpdateForm.java
package study;

import java.util.List;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
//import com.opensymphony.xwork2.ActionContext;
//import javax.servlet.http.HttpServletRequest;


public class UpdateForm extends ActionSupport{
private int stu_id;
private String sid;
private String stuName;
private String address;
private String stuPhone;
private Student student;
private List<Student> students;
private Map session;
private String pageNow;
//private HttpServletRequest request;
public String execute(){
//session = ActionContext.getContext().getSession();
//request = ServletActionContext.getRequest();
//sid = request.getParameter("sid");
session = ServletActionContext.getContext().getSession();
sid = ServletActionContext.getRequest().getParameter("sid");
if(sid!=null){
stu_id = Integer.parseInt(sid);
}
students = (List)session.get("students");
if(students!=null){
student = students.get(stu_id);
stu_id = student.getStu_id();
stuName = student.getStuName();
stuPhone = student.getStuPhone();
address = student.getAddress();
}
return SUCCESS;
}
public int getStu_id(){
return stu_id;
}
public void setStu_id(int stu_id){
this.stu_id=stu_id;
}
public String getSid(){
return sid;
}
public void setSid(String sid){
this.sid=sid;
}
public String getStuName(){
return stuName;
}
public void setStuName(String stuName){
this.stuName=stuName;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address=address;
}
public String getStuPhone(){
return stuPhone;
}
public void setStuPhone(String stuPhone){
this.stuPhone=stuPhone;
}
public Student getStudent(){
return student;
}
public void setStudent(Student student){
this.student=student;
}
public String getPageNow(){
return pageNow;
}
public void setPageNow(String pageNow){
this.pageNow=pageNow;
}
}
======================================
UpdateSuccess.java
package study;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

public class UpdateSuccess extends ActionSupport {
private String stuName;
private String stuPhone;
private String address;
private int stu_id;
private String pageNow;
private StudentDAO stuDAO = new StudentDAO();

public String execute()throws Exception{
pageNow = ServletActionContext.getRequest().getParameter("pageNow");
if(pageNow==null){
 pageNow="";
}
stuDAO.student_Update(stuName, stuPhone, address, stu_id);
return SUCCESS;
}
public String getStuName(){
return stuName;
}
public void setStuName(String stuName){
this.stuName=stuName;
}
public String getStuPhone(){
return stuPhone;
}
public void setStuPhone(String stuPhone){
this.stuPhone=stuPhone;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address=address;
}
public int getStu_id(){
return stu_id;
}
public void setStu_id(int stu_id){
this.stu_id=stu_id;
}
public String getPageNow(){
return pageNow;
}
public void setPageNow(String pageNow){
this.pageNow=pageNow;
}
}
=======================================
InsertForm.java
package study;
import com.opensymphony.xwork2.ActionSupport;

public class InsertForm extends ActionSupport {
private String pageNow;
public String execute(){
return SUCCESS;
}
public String getPageNow(){
return pageNow;
}
public void setPageNow(String pageNow){
this.pageNow=pageNow;
}
}
======================================
InsertSuccess.java
package study;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.opensymphony.xwork2.ActionSupport;

public class InsertSuccess extends ActionSupport{
private String stuName;
private String stuPhone;
private String address;

private StudentDAO stuDAO = new StudentDAO();

public String execute()throws Exception{
stuDAO.student_Insert(stuName, stuPhone, address);
return SUCCESS;
}
public String getStuName(){
return stuName;
}
public void setStuName(String stuName){
this.stuName=stuName;
}
public String getStuPhone(){
return stuPhone;
}
public void setStuPhone(String stuPhone){
this.stuPhone=stuPhone;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address=address;
}
}
=========================================
DeleteSuccess.java
package study;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
//import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import java.util.List;
import java.util.Map;

//import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DeleteSuccess extends ActionSupport {
private int stu_id;
private String sid;
private String stuName;
//private HttpServletRequest request;
private Map session;
private List<Student> students;
private Student student;
private StudentDAO stuDAO = new StudentDAO();

public String execute()throws Exception{
//session = ActionContext.getContext().getSession();
//request = ServletActionContext.getRequest();
//sid = request.getParameter("sid");
session = ServletActionContext.getContext().getSession();
sid = ServletActionContext.getRequest().getParameter("sid");
if(sid!=null){
 stu_id = Integer.parseInt(sid);
}
students=(List)session.get("students");
if(students!=null){
 student = students.get(stu_id);
 stu_id = student.getStu_id();
 stuName = student.getStuName();
}
stuDAO.student_Delete(stu_id);
return SUCCESS;
}
public int getStu_id(){
return stu_id;
}
public void setStu_id(int stu_id){
this.stu_id=stu_id;
}
public String getStuName(){
return stuName;
}
public void setStuName(String stuName){
this.stuName=stuName;
}
public void setSession(Map session){
this.session=session;
}
public Map getSession(){
return session;
}
public String getSid(){
return sid;
}
public void setSid(String sid){
this.sid=sid;
}
}
===========================================
9.製作Validation
InsertSuccess-validation.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="stuName">
<field-validator type="requiredstring">
<message key="stuName.required"/>
</field-validator>
</field>
<field name="stuPhone">
<field-validator type="requiredstring">
<message key="stuPhone.required"></message>
</field-validator>
</field>
<field name="address">
<field-validator type="requiredstring">
<message key="address.required"/>
</field-validator>
</field>
</validators>
============================================
InsertSuccess.properties
stuName.required=Name field is required.
stuPhone.required=Telephone field is required.
address.required=Address field is required.
=============================================
10.製作Struts.xml,將Action與Result配對
<?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">
<global-results>
<result name="error">/Error.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping result="error" exception="java.lang.Exception"></exception-mapping>
</global-exception-mappings>
<action name="main" class="study.Main">
<result>/index.jsp</result>
</action>
<action name="show" class="study.ShowAction">
<result name="success">/show.jsp</result>
<result name="error">/Error.jsp</result>
<result name="input">/index.jsp</result>
</action>
<action name="updateForm" class="study.UpdateForm">
<result>/updateForm.jsp</result>
</action>
<action name="update" class="study.UpdateSuccess">
<result>/updateSuccess.jsp</result>
</action>
<action name="insertForm" class="study.InsertForm">
<result>/insertForm.jsp</result>
</action>
<action name="insert" class="study.InsertSuccess">
<result>/insertSuccess.jsp</result>
<result name="input">/insertForm.jsp</result>
</action>
<action name="delete" class="study.DeleteSuccess">
<result>/deleteSuccess.jsp</result>
</action>
<action name="showDetail" class="study.UpdateForm">
<result>/showDetail.jsp</result>
</action>
</package>
</struts>
=============================================
11.啟動Tomcat Server執行網頁,其測試結果如下圖:

沒有留言:

張貼留言