Java+MyEclipse+Tomcat (六)詳解Servlet和DAO資料庫增刪改查操作
Java+MyEclipse+Tomcat (一)配置過程及jsp網站開發入門
Java+MyEclipse+Tomcat (二)配置Servlet及簡單實現表單提交
Java+MyEclipse+Tomcat (三)配置MySQL及查詢資料顯示在JSP網頁中
Java+MyEclipse+Tomcat (四)Servlet提交表單和資料庫操作
Java+MyEclipse+Tomcat (五)DAO和Java Bean實現資料庫和介面分開操作
免費資源下載地址:
http://download.csdn.net/detail/eastmount/8733385
PS:這篇文章可以認為是對前面五篇文章的一系列總結和應用,同時我認為理解該篇文章基本就能簡單實現一個基於資料庫操作的JSP網站,對你的課程專案或畢設有所幫助!但同時沒有涉及事務、觸發器、儲存過程、併發處理等資料庫知識,也沒有Struts、Hibernate、Spring框架知識,它還是屬於基礎性文章吧!希望對你有所幫助~
一. 專案結構
該專案的結構如下圖所示:
二. 資料庫初始化操作
開啟MySQL,輸入預設超級root使用者的密碼,然後資料庫的操作如下程式碼:
--建立資料庫
create database ManageTrain;
--使用資料庫
use ManageTrain;
--建立表 車次資訊管理表 主鍵:車次
--屬性:車次 出發地 目的地 行車時間 硬座票價 軟座票價 硬臥票價 軟臥票價 車輛路線
create table TrainManage(
trainid varchar(20) primary key,
start varchar(20),
end varchar(20),
time varchar(20),
yzprice decimal(10,1),
rzprice decimal(10,1),
ywprice decimal(10,1),
rwprice decimal(10,1),
root varchar(200)
);
--插入資料
insert TrainManage (trainid,start,end,time,yzprice,rzprice,ywprice,rwprice,root)
values ("T87","Beijing","Guiyang","28小時","278","320","464.5","550",
"Beijing Shijiazhuang Guiyang");
insert TrainManage (trainid,start,end,time,yzprice,rzprice,ywprice,rwprice,root)
values ("T87","Guiyang","Beijing","28小時","278","320","464.5","550",
"Guiyang Shijiazhuang Beijing");
--查詢資料
select * from TrainManage;
注意:上面操作在MySQL黑框中輸出增刪改查的SQL語言就可以,不要把中文註釋也執行。同時設定所有編碼方式都統一為utf-8防止亂碼,資料庫表結構如下圖所示:三. 簡單查詢操作DAO方法
新建Web Project,專案名為“TrainDatabase”,對火車車次資料庫的增刪改查。
執行效果如下圖所示:
主要是呼叫getConnection(url, userName, password)方法進行連線資料庫操作,資料庫的名稱為TrainManage,預設的連線物件為root,密碼為123456。同時定義兩個函式executeUpdate()執行無引數的SQL語句操作和有引數的SQL語句操作。
package util;
import java.sql.*;
import com.mysql.jdbc.Driver;
public class JDBCConnect {
//獲取預設資料庫連線
public static Connection getConnection() throws SQLException {
return getConnection("ManageTrain", "root", "123456"); //資料庫名 預設使用者 密碼
}
//連線資料庫 引數:資料庫名 root登入名 密碼
public static Connection getConnection(String dbName, String userName,
String password) throws SQLException {
String url = "jdbc:mysql://localhost:3306/" + dbName
+ "?characterEncoding=utf-8";
//連線MySQL"com.mysql.jdbc.Driver"
DriverManager.registerDriver(new Driver());
return DriverManager.getConnection(url, userName, password);
}
//設定 PreparedStatement 引數
public static void setParams(PreparedStatement preStmt, Object... params)
throws SQLException {
if (params == null || params.length == 0)
return;
for (int i = 1; i <= params.length; i++) {
Object param = params[i - 1];
if (param == null) {
preStmt.setNull(i, Types.NULL);
} else if (param instanceof Integer) {
preStmt.setInt(i, (Integer) param);
} else if (param instanceof String) {
preStmt.setString(i, (String) param);
} else if (param instanceof Double) {
preStmt.setDouble(i, (Double) param);
} else if (param instanceof Long) {
preStmt.setDouble(i, (Long) param);
} else if (param instanceof Timestamp) {
preStmt.setTimestamp(i, (Timestamp) param);
} else if (param instanceof Boolean) {
preStmt.setBoolean(i, (Boolean) param);
} else if (param instanceof Date) {
preStmt.setDate(i, (Date) param);
}
}
}
//執行 SQL,返回影響的行數 異常處理
public static int executeUpdate(String sql) throws SQLException {
return executeUpdate(sql, new Object[] {});
}
//帶引數執行SQL,返回影響的行數 異常處理
public static int executeUpdate(String sql, Object... params)
throws SQLException {
Connection conn = null;
PreparedStatement preStmt = null;
try {
conn = getConnection();
preStmt = conn.prepareStatement(sql);
setParams(preStmt, params);
return preStmt.executeUpdate(); //執行SQL操作
} finally {
if (preStmt != null)
preStmt.close();
if (conn != null)
conn.close();
}
}
}
2.在src下新建資料夾bean,然後新增類TrainManage.java。程式碼如下:
package bean;
public class TrainManage {
private String trainid; //車次
private String start; //出發地
private String end; //目的地
private String time; //行車時間
private float yzprice; //硬座票價
private float rzprice; //軟座票價
private float ywprice; //硬臥票價
private float rwprice; //軟臥票價
private String root; //車輛路線
public String getTrainid() { return trainid; }
public String getStart() { return start; }
public String getEnd() { return end; }
public String getTime() { return time; }
public Float getYzprice() { return yzprice; }
public Float getRzprice() { return rzprice; }
public Float getYwprice() { return ywprice; }
public Float getRwprice() { return rwprice; }
public String getRoot() { return root; }
public void setTrainid(String str) { this.trainid = str; }
public void setStart(String str) { this.start = str; }
public void setEnd(String str) { this.end = str; }
public void setTime(String str) { this.time = str; }
public void setYzprice(Float price) { this.yzprice = price; }
public void setRzprice(Float price) { this.rzprice = price; }
public void setYwprice(Float price) { this.ywprice = price; }
public void setRwprice(Float price) { this.rwprice = price; }
public void setRoot(String str) { this.root = str; }
}
3.在src下新建資料夾DAO,然後新增類StudentDAO.java。程式碼如下:通常DAO(Data Access Object)資料訪問物件是負責與資料庫連線,主要功能執行對資料表的CUDR操作(建立、更新、刪除、查詢)。每個資料表都定義一個DAO介面或類實現,實現對此表的讀寫操作。換句話說,就是在域名.專案.模組.dao資料夾下建立個DAO類即可。
package DAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import bean.TrainManage;
import util.JDBCConnect;
public class TrainManageDAO {
//插入車次
public static int insert(TrainManage train) throws Exception {
String sql = "INSERT INTO TrainManage (trainid,start,end,time,yzprice,rzprice,ywprice,rwprice,root) " +
"VALUES ('" + train.getTrainid() +"','"+ train.getStart() +"','"+ train.getEnd() +
"','"+ train.getTime() +"','"+ train.getYzprice() +"','"+ train.getRzprice() +
"','"+ train.getYwprice() +"','"+ train.getRwprice() +"','"+ train.getRoot() +"');";
System.out.println(sql);
return JDBCConnect.executeUpdate(sql);
/**
* 總是報錯 No value specified for parameter 5
* 很多原因是 insert into train (?,?,?) values (?,?,?) 前面不應該是問號
* 但我的懷疑是引數過多使用executeUpdate(sql,?,?,?...)方法是錯誤
*
* String sql = "INSERT INTO TrainManage (trainid,start,end,time,yzprice,rzprice,ywprice,rwprice,root) VALUES (?,?,?,?,?,?,?,?,?);";
* System.out.println(sql);
* return JDBCConnect.executeUpdate(sql, train.getTrainid(), train.getStart(), train.getEnd(),
* train.getTime(), train.getYzprice(), train.getRzprice(), train.getYwprice(),
* train.getRwprice(), train.getRoot());
*/
}
//更新車次
public static int update(TrainManage train) throws Exception {
String sql = "UPDATE TrainManage SET start = ?, end = ? WHERE trainid = ? ";
return JDBCConnect.executeUpdate(sql, train.getStart(), train.getEnd(), train.getTrainid());
}
//刪除操作
public static int delete(String id) throws Exception {
String sql = "DELETE FROM TrainManage WHERE trainid = ? ";
return JDBCConnect.executeUpdate(sql, id);
}
//查詢記錄 某車次
public static TrainManage find(String id) throws Exception {
String sql = "SELECT * FROM TrainManage WHERE trainid = ? ";
Connection conn = null;
PreparedStatement preStmt = null;
ResultSet rs = null;
try {
//連結資料庫執行SQL語句
conn = JDBCConnect.getConnection(); //連線預設資料庫
preStmt = conn.prepareStatement(sql);
preStmt.setString(1, id);
rs = preStmt.executeQuery();
//獲取查詢結果
if (rs.next()) {
TrainManage train = new TrainManage();
train.setTrainid(rs.getString("trainid"));
train.setStart(rs.getString("start"));
train.setEnd(rs.getString("end"));
train.setTime(rs.getString("time"));
train.setYzprice(rs.getFloat("yzprice"));
train.setYwprice(rs.getFloat("ywprice"));
train.setRzprice(rs.getFloat("rzprice"));
train.setRwprice(rs.getFloat("rwprice"));
train.setRoot(rs.getString("root"));
return train;
} else {
return null;
}
} finally { //依次關閉 記錄集 宣告 連線物件
if (rs != null)
rs.close();
if (preStmt != null)
preStmt.close();
if (conn != null)
conn.close();
}
}
//查詢記錄 起始站 達到站
public static List<TrainManage> findStartEnd(String start,String end) throws Exception {
List<TrainManage> list = new ArrayList<TrainManage>();
String sql = null;
Connection conn = null;
Statement statement = null;
ResultSet rs = null;
//判斷SQL語句
if(start==""&&end=="") {
sql = "SELECT * FROM TrainManage;";
} else if(end=="") {
sql = "SELECT * FROM TrainManage WHERE start = '"+ start + "';";
} else if(start=="") {
sql = "SELECT * FROM TrainManage WHERE end = '"+ end + "';";
} else {
sql = "SELECT * FROM TrainManage WHERE start = '"
+ start + "' and end = '"+ end +"';";
}
//執行
try {
//連結資料庫執行SQL語句
conn = JDBCConnect.getConnection(); //連線預設資料庫
statement = conn.createStatement();
System.out.println(start+" "+end);
System.out.println(sql);
rs = statement.executeQuery(sql);
//獲取查詢結果
while(rs.next()) {
TrainManage train = new TrainManage();
train.setTrainid(rs.getString("trainid"));
train.setStart(rs.getString("start"));
train.setEnd(rs.getString("end"));
train.setTime(rs.getString("time"));
train.setYzprice(rs.getFloat("yzprice"));
train.setYwprice(rs.getFloat("ywprice"));
train.setRzprice(rs.getFloat("rzprice"));
train.setRwprice(rs.getFloat("rwprice"));
train.setRoot(rs.getString("root"));
list.add(train);
}
} catch (Exception e) {
System.out.println("錯誤:"+e.getMessage());
}
finally { //依次關閉 記錄集 宣告 連線物件
if (rs != null)
rs.close();
if (statement != null)
statement.close();
if (conn != null)
conn.close();
}
return list;
}
//查詢所有車次資訊
public static List<TrainManage> listStudents() throws Exception {
List<TrainManage> list = new ArrayList<TrainManage>();
String sql = "SELECT * FROM TrainManage";
Connection conn = null;
PreparedStatement preStmt = null;
ResultSet rs = null;
try {
conn = JDBCConnect.getConnection();
preStmt = conn.prepareStatement(sql);
rs = preStmt.executeQuery();
while (rs.next()) {
//設定資料庫中表引數 否則報錯java.sql.SQLException: Column 'id' not found.
TrainManage train = new TrainManage();
train.setTrainid(rs.getString("trainid"));
train.setStart(rs.getString("start"));
train.setEnd(rs.getString("end"));
train.setTime(rs.getString("time"));
train.setYzprice(rs.getFloat("yzprice"));
train.setYwprice(rs.getFloat("ywprice"));
train.setRzprice(rs.getFloat("rzprice"));
train.setRwprice(rs.getFloat("rwprice"));
train.setRoot(rs.getString("root"));
list.add(train);
}
} finally {
if (rs != null)
rs.close();
if (preStmt != null)
preStmt.close();
if (conn != null)
conn.close();
}
return list;
}
}
4.在WebRoot資料夾下建立trainManage.jsp檔案,頁面佈局程式碼如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<jsp:directive.page import="DAO.TrainManageDAO"/>
<jsp:directive.page import="java.util.List"/>
<%
List trainList = TrainManageDAO.listStudents();
request.setAttribute("trainList", trainList);
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>火車卡訂票系統管理系統</title>
</head>
<body>
<div align="center">
<div class="trainCSS">
<table width="1024" height="150" cellpadding="0" cellspacing="0">
<tr><td colspan="2">
<img src="./image/logo.jpg" alt="logo" width="1024" height="149">
</td></tr>
<tr><td width="205" bgcolor="#b7d7ec">
<p align="center">
<script language=JavaScript>
today=new Date();
function initArray(){
this.length=initArray.arguments.length;
for(var i=0;i<this.length;i++)
this[i+1]=initArray.arguments[i]; }
var d=new initArray(
"星期日","星期一","星期二","星期三","星期四", "星期五","星期六");
document.write("<font color=##ff0000 style='font-size:12pt;font-family: 宋體'> ",
today.getYear()+1900,"年",today.getMonth()+1,"月",today.getDate(),"日 ",d[today.getDay()+1],
"</font>" );
</script>
</p>
</td>
<td width="819" bgcolor="#b7d7ec">
<marquee direction="left" onmouseover=this.stop() onmouseout=this.start() scrollAmount=3 scrollDelay=100>
<FONT style="FONT-SIZE: 18px"color=blue>歡迎使用火車票訂票系統管理系統 ,如有不足,敬請指導!</FONT>
</marquee>
</td>
</tr>
<tr><td height="12"></td></tr>
</table>
</div>
<div class="trainCSS">
<table border="0" width="1024" cellpadding="0" cellspacing="0">
<tr><td width="130" bgcolor="#dfeaf1" valign="top">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr><td height="10"></td></tr>
<tr><td align="center"> <font size="3" color="blue">管理員:xxx,歡迎您!</font></td></tr>
<tr><td height="10"></td></tr>
<tr>
<td align="center"><p><a href="trainManage.jsp">
<img src="image/ccxxgl-xz.jpg" width="194" height="37" border="0"></a><td> </td>
</tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="buyManage.jsp">
<img src="image/dpgl.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="peopleManage.jsp">
<img src="image/hygl.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="serverManage.jsp">
<img src="image/spqktj.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="infoManage.jsp">
<img src="image/lygl.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="exitManage.jsp">
<img src="image/exit.jpg" width="194" height="37" border="0"></a>
</td></tr>
</table>
</td>
<td>
<table width="100%" height="350" border="1" cellpadding="0" cellspacing="0" bgcolor="#dfeaf1">
<tr><TD align="center" valign="top" style="padding-left:20px;padding-top:10px;">
<div align="left">當前位置: <a href="homepage.jsp">首頁</a> > 車次資訊管理</div>
<br /><br />
<form action="trainManageSelect.jsp" method="post">
<!-- html:form為struts -->
出發地: <input type="text" id="start" name="start" style='font-size:18px' width=200/>
到達地: <input type="text" id="end" name="end" style='font-size:18px'/><br /><br />
<input type="submit" name="Select" value="查詢車次" style='font-size:18px'/>
<a href="trainManageInsert.jsp" style='font-size:20px'>插入車次</a>
</form>
<table border="2" bordercolor="#12A0F5">
<tr align=center>
<td>火車列次</td><td>出發地</td><td>目的地</td><td>行車時間</td>
<td>硬座票價</td><td>軟座票價</td><td>硬臥票價</td><td>軟臥票價</td>
<td>車輛路線</td><td>資訊操作</td>
</tr>
<c:forEach items="${trainList}" var="train">
<tr align=center>
<td>${train.trainid}</td>
<td>${train.start}</td>
<td>${train.end}</td>
<td>${train.time}</td>
<td>${train.yzprice}</td>
<td>${train.rzprice}</td>
<td>${train.ywprice}</td>
<td>${train.rwprice}</td>
<td>
<A href="trainManageDetail.jsp?action=see&id=${train.trainid}">檢視</A></td>
<td>
<a href="trainManageUpdate.jsp?action=edit&id=${train.trainid}">修改</a>
<a href="trainManageDelete.jsp?action=del&id=${train.trainid}"
onclick="return confirm('確定刪除?')">刪除</a>
</td>
</tr>
</c:forEach>
</table>
<br /><br />
</TD></tr>
</table>
</td>
</tr>
<tr><td height="20"></td></tr>
</table>
</div>
<div class="div">
<!-- 底部版權所有介面 -->
<TABLE class=wrapper border=0 cellSpacing=0 cellPadding=0 width="100%" align=center>
<TBODY>
<TR><TD style="LINE-HEIGHT: 100%" align="center">
<HR style="WIDTH: 96%; HEIGHT: 4px; COLOR: #02457c">
<font size="2"> <SCRIPT language=javascript src=""></SCRIPT>
<!-- target=_blank開啟新的網頁 -->
<BR><A href="aboutme.jsp">關於我們</A> | <A href="wzsm.jsp"
>網站宣告</A> <BR>版權所有©2014-2015 北京郵電大學 Eastmount <BR>
京ICP備10009636號 </font>
</TD></TR>
</TBODY>
</TABLE>
</div>
</div>
</body>
</html>
5在WebRoot路徑下建立image資料夾,並新增jsp中需要使用的圖片資源。6.在WebRoot/WEB-INF/lib資料夾中新增mysql-connector-java-5.1.15-bin.jar檔案,訪問MySQL資料庫需要用到。
7.右鍵專案,Run As在Tomcat 7.x下即可執行,效果如前圖所示。
其中JSP檔案與DAO的互動核心程式碼如下:
<jsp:directive.page import="DAO.TrainManageDAO"/>
<jsp:directive.page import="java.util.List"/>
<%
List trainList = TrainManageDAO.listStudents();
request.setAttribute("trainList", trainList);
%>
...
<table border="2" bordercolor="#12A0F5">
<tr align=center>
<td>火車列次</td><td>出發地</td><td>目的地</td><td>行車時間</td>
<td>硬座票價</td><td>軟座票價</td><td>硬臥票價</td><td>軟臥票價</td>
<td>車輛路線</td><td>資訊操作</td>
</tr>
<c:forEach items="${trainList}" var="train">
<tr align=center>
<td>${train.trainid}</td>
<td>${train.start}</td>
<td>${train.end}</td>
<td>${train.time}</td>
<td>${train.yzprice}</td>
<td>${train.rzprice}</td>
<td>${train.ywprice}</td>
<td>${train.rwprice}</td>
<td><A href="trainManageDetail.jsp?action=see&id=${train.trainid}">檢視</A></td>
<td>
<a href="trainManageUpdate.jsp?action=edit&id=${train.trainid}">修改</a>
<a href="trainManageDelete.jsp?action=del&id=${train.trainid}"
onclick="return confirm('確定刪除?')">刪除</a>
</td>
</tr>
</c:forEach>
</table>
四. 關鍵字查詢操作
關鍵字查詢執行截圖如下圖所示:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<jsp:directive.page import="DAO.TrainManageDAO"/>
<jsp:directive.page import="bean.TrainManage"/>
<jsp:directive.page import="java.util.List"/>
<%
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String mstart = request.getParameter("start");
String mend = request.getParameter("end");
List<TrainManage> trainList = TrainManageDAO.findStartEnd(mstart,mend);
//List trainList = TrainManageDAO.listStudents();
request.setAttribute("trainList", trainList);
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>火車卡訂票系統管理系統</title>
</head>
<body>
<div align="center">
<div class="trainCSS">
<table width="1024" height="150" cellpadding="0" cellspacing="0">
<tr><td colspan="2">
<img src="./image/logo.jpg" alt="logo" width="1024" height="149">
</td></tr>
<tr><td width="205" bgcolor="#b7d7ec">
<p align="center">
<script language=JavaScript>
today=new Date();
function initArray(){
this.length=initArray.arguments.length;
for(var i=0;i<this.length;i++)
this[i+1]=initArray.arguments[i]; }
var d=new initArray(
"星期日","星期一","星期二","星期三","星期四", "星期五","星期六");
document.write("<font color=##ff0000 style='font-size:12pt;font-family: 宋體'> ",
today.getYear()+1900,"年",today.getMonth()+1,"月",today.getDate(),"日 ",d[today.getDay()+1],
"</font>" );
</script>
</p>
</td>
<td width="819" bgcolor="#b7d7ec">
<marquee direction="left" onmouseover=this.stop() onmouseout=this.start() scrollAmount=3 scrollDelay=100>
<FONT style="FONT-SIZE: 18px"color=blue>歡迎使用火車票訂票系統管理系統 ,如有不足,敬請指導!</FONT>
</marquee>
</td>
</tr>
<tr><td height="12"></td></tr>
</table>
</div>
<div class="trainCSS">
<table border="0" width="1024" cellpadding="0" cellspacing="0">
<tr><td width="130" bgcolor="#dfeaf1" valign="top">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr><td height="10"></td></tr>
<tr><td align="center"> <font size="3" color="blue">管理員:xxx,歡迎您!</font></td></tr>
<tr><td height="10"></td></tr>
<tr>
<td align="center"><p><a href="trainManage.jsp">
<img src="image/ccxxgl-xz.jpg" width="194" height="37" border="0"></a><td> </td>
</tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="buyManage.jsp">
<img src="image/dpgl.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="peopleManage.jsp">
<img src="image/hygl.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="serverManage.jsp">
<img src="image/spqktj.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="infoManage.jsp">
<img src="image/lygl.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="exitManage.jsp">
<img src="image/exit.jpg" width="194" height="37" border="0"></a>
</td></tr>
</table>
</td>
<td>
<table width="100%" height="350" border="1" cellpadding="0" cellspacing="0" bgcolor="#dfeaf1">
<tr><TD align="center" valign="top" style="padding-left:20px;padding-top:10px;">
<div align="left">當前位置: <a href="homepage.jsp">首頁</a> > 車次資訊管理</div>
<br /><br />
<form action="trainManageSelect.jsp" method="post">
<!-- html:form為struts -->
出發地: <input type="text" id="start" name="start" style='font-size:18px' width=200/>
到達地: <input type="text" id="end" name="end" style='font-size:18px'/><br /><br />
<input type="submit" name="Select" value="查詢車次" style='font-size:18px'/>
<a href="trainManageInsert.jsp" style='font-size:20px'>插入車次</a>
</form>
<table border="2" bordercolor="#12A0F5">
<tr align=center>
<td>火車列次</td><td>出發地</td><td>目的地</td><td>行車時間</td>
<td>硬座票價</td><td>軟座票價</td><td>硬臥票價</td><td>軟臥票價</td>
<td>車輛路線</td><td>資訊操作</td>
</tr>
<c:forEach items="${trainList}" var="train">
<tr align=center>
<td>${train.trainid}</td>
<td>${train.start}</td>
<td>${train.end}</td>
<td>${train.time}</td>
<td>${train.yzprice}</td>
<td>${train.rzprice}</td>
<td>${train.ywprice}</td>
<td>${train.rwprice}</td>
<td>
<A href="trainManageDetail.jsp?action=see&id=${train.trainid}">檢視</A></td>
<td>
<a href="trainManageUpdate.jsp?action=edit&id=${train.trainid}">修改</a>
<a href="trainManageDelete.jsp?action=del&id=${train.trainid}"
onclick="return confirm('確定刪除?')">刪除</a>
</td>
</tr>
</c:forEach>
</table>
<br /><br />
</TD></tr>
</table>
</td>
</tr>
<tr><td height="20"></td></tr>
</table>
</div>
<div class="div">
<!-- 底部版權所有介面 -->
<TABLE class=wrapper border=0 cellSpacing=0 cellPadding=0 width="100%" align=center>
<TBODY>
<TR><TD style="LINE-HEIGHT: 100%" align="center">
<HR style="WIDTH: 96%; HEIGHT: 4px; COLOR: #02457c">
<font size="2"> <SCRIPT language=javascript src=""></SCRIPT>
<!-- target=_blank開啟新的網頁 -->
<BR><A href="aboutme.jsp">關於我們</A> | <A href="wzsm.jsp"
>網站宣告</A> <BR>版權所有©2014-2015 北京郵電大學 Eastmount <BR>
京ICP備10009636號 </font>
</TD></TR>
</TBODY>
</TABLE>
</div>
</div>
</body>
</html>
呼叫的trainManageDAO.java中的函式findStartEnd(String start,String end)如下,它如果不輸入則進行所有查詢,也支援單方面出發或到達查詢://查詢記錄 某車次
public static List<TrainManage> findStartEnd(String start,String end) throws Exception {
List<TrainManage> list = new ArrayList<TrainManage>();
String sql = null;
Connection conn = null;
Statement statement = null;
ResultSet rs = null;
//判斷SQL語句
if(start==""&&end=="") {
sql = "SELECT * FROM TrainManage;";
} else if(end=="") {
sql = "SELECT * FROM TrainManage WHERE start = '"+ start + "';";
} else if(start=="") {
sql = "SELECT * FROM TrainManage WHERE end = '"+ end + "';";
} else {
sql = "SELECT * FROM TrainManage WHERE start = '"
+ start + "' and end = '"+ end +"';";
}
//執行
try {
//連結資料庫執行SQL語句
conn = JDBCConnect.getConnection(); //連線預設資料庫
statement = conn.createStatement();
System.out.println(start+" "+end);
System.out.println(sql);
rs = statement.executeQuery(sql);
//獲取查詢結果
while(rs.next()) {
TrainManage train = new TrainManage();
train.setTrainid(rs.getString("trainid"));
train.setStart(rs.getString("start"));
train.setEnd(rs.getString("end"));
train.setTime(rs.getString("time"));
train.setYzprice(rs.getFloat("yzprice"));
train.setYwprice(rs.getFloat("ywprice"));
train.setRzprice(rs.getFloat("rzprice"));
train.setRwprice(rs.getFloat("rwprice"));
train.setRoot(rs.getString("root"));
list.add(train);
}
} catch (Exception e) {
System.out.println("錯誤:"+e.getMessage());
}
finally { //依次關閉 記錄集 宣告 連線物件
if (rs != null)
rs.close();
if (statement != null)
statement.close();
if (conn != null)
conn.close();
}
return list;
}
其中核心步驟如下:1.在trainManage.jsp提交POST表單出發地(<input id="start")和到達地(<input id="end"),提交給trainManageSelect.jsp;
2.在trainManageSelect.jsp中通過獲取出發地和到達地,並執行DAO中的TrainManageDAO.java中關鍵字查詢函式:
String mstart = request.getParameter("start");
String mend = request.getParameter("end");
List<TrainManage> trainList = TrainManageDAO.findStartEnd(mstart,mend);
request.setAttribute("trainList", trainList);
3.在JSP中通過EL迴圈顯示結果如下:
<c:forEach items="${trainList}" var="train">
<tr align=center>
<td>${train.trainid}</td>
<td>${train.start}</td>
...
</tr>
</c:forEach>
PS:同時在這過程中你會遇到執行關鍵字中文查詢時顯示亂碼。
在trainManageSelect.java檔案中通過函式findStartEnd(start,end)打樁輸出提交表單"北京 長沙"如下所示:
第一個方面是在進行SQL查詢時,我最初使用的第一種方法核心程式碼:
String sql = "SELECT * FROM TrainManage WHERE start = ? and end = ? ;";
Connection conn = JDBCConnect.getConnection(); //連線預設資料庫
PreparedStatement preStmt = conn.prepareStatement(sql);
preStmt.setString(1, start);
preStmt.setString(2, end);
ResultSet rs = preStmt.executeQuery();
但是在查詢英文Beijing => Guizhou 時能正確顯示,而中文就沒有結果,後改為帶引號("'"+string+"'")的引數方式,核心程式碼如下:String sql = "SELECT * FROM TrainManage WHERE start = '"
+ start + "' and end = '"+ end +"';";
Connection conn = JDBCConnect.getConnection(); //連線預設資料庫
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sql);
while(rs.next()){...}
後來使用該方法仍然存在亂碼,但是這次我發現了原因,在form提交表單時採用Get方法就會出現中文亂碼,雖然URL中顯示的是:http://localhost:8080/TrainDatabase/trainManageSelect.jsp?start=北京&end=長沙&sumbit=提交
但是可能URL轉String出現亂碼的,改為POST即可實現正常查詢,顯示正常中文。
注意:前提是我的所有編碼字符集都統一為UTF-8。
五. 插入操作呼叫Servlet
該部分執行截圖如下圖所示:
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import bean.TrainManage;
import util.JDBCConnect;
import DAO.TrainManageDAO;
public class InsertTrainAction extends HttpServlet {
public InsertTrainAction() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
//The doGet method of the servlet
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
//The doPost method of the servlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8"); //設定輸出編碼
request.setCharacterEncoding("UTF-8");
try {
//插入資料庫
String m_trainid = request.getParameter("trainid");
String m_start = request.getParameter("start");
String m_end = request.getParameter("end");
String m_time = request.getParameter("time");
String m_yz = request.getParameter("yzprice");
Float m_yzprice = Float.parseFloat(m_yz);
String m_rz = request.getParameter("rzprice");
Float m_rzprice = Float.parseFloat(m_rz);
String m_yw = request.getParameter("ywprice");
Float m_ywprice = Float.parseFloat(m_yw);
String m_rw = request.getParameter("rwprice");
Float m_rwprice = Float.parseFloat(m_rw);
String m_root = request.getParameter("root");
TrainManage train = new TrainManage();
train.setTrainid(m_trainid);
train.setStart(m_start);
train.setEnd(m_end);
train.setTime(m_time);
train.setYzprice(m_yzprice);
train.setRzprice(m_rzprice);
train.setYwprice(m_ywprice);
train.setRwprice(m_rwprice);
train.setRoot(m_root);
int success = TrainManageDAO.insert(train);
request.setAttribute("success", success);
//設定全路徑 否則trainManage.jsp跳轉到servlet/trainManage.jsp路徑下不存在
response.sendRedirect("http://localhost:8080/TrainDatabase/trainManage.jsp");
} catch(Exception e) {
System.out.println("錯誤:"+e.getMessage());
response.sendRedirect("http://localhost:8080/TrainDatabase/trainManage.jsp");
}
}
public void init() throws ServletException {
// Put your code here
}
}
它會自動配置WebRoot/WEB-INF/web.xml檔案中servlet和其對映。同時在WebRoot中新增trainManageInsert.jsp。<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session = "true" %>
<jsp:directive.page import="DAO.TrainManageDAO"/>
<jsp:directive.page import="bean.TrainManage"/>
<jsp:directive.page import="java.util.List"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>火車卡訂票系統管理系統</title>
</head>
<body>
<div align="center">
<div class="trainCSS">
<table width="1024" height="150" cellpadding="0" cellspacing="0">
<tr><td colspan="2">
<img src="./image/logo.jpg" alt="logo" width="1024" height="149">
</td></tr>
<tr><td width="205" bgcolor="#b7d7ec">
<p align="center">
<script language=JavaScript>
today=new Date();
function initArray(){
this.length=initArray.arguments.length;
for(var i=0;i<this.length;i++)
this[i+1]=initArray.arguments[i]; }
var d=new initArray(
"星期日","星期一","星期二","星期三","星期四", "星期五","星期六");
document.write("<font color=##ff0000 style='font-size:12pt;font-family: 宋體'> ",
today.getYear()+1900,"年",today.getMonth()+1,"月",today.getDate(),"日 ",d[today.getDay()+1],
"</font>" );
</script>
</p>
</td>
<td width="819" bgcolor="#b7d7ec">
<marquee direction="left" onmouseover=this.stop() onmouseout=this.start() scrollAmount=3 scrollDelay=100>
<FONT style="FONT-SIZE: 18px"color=blue>歡迎使用火車票訂票系統管理系統 ,如有不足,敬請指導!</FONT>
</marquee>
</td>
</tr>
<tr><td height="12"></td></tr>
</table>
</div>
<div class="trainCSS">
<table border="0" width="1024" cellpadding="0" cellspacing="0">
<tr><td width="130" bgcolor="#dfeaf1" valign="top">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr><td height="10"></td></tr>
<tr><td align="center"> <font size="3" color="blue">管理員:xxx,歡迎您!</font></td></tr>
<tr><td height="10"></td></tr>
<tr>
<td align="center"><p><a href="trainManage.jsp">
<img src="image/ccxxgl-xz.jpg" width="194" height="37" border="0"></a><td> </td>
</tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="buyManage.jsp">
<img src="image/dpgl.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="peopleManage.jsp">
<img src="image/hygl.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="serverManage.jsp">
<img src="image/spqktj.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="infoManage.jsp">
<img src="image/lygl.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="exitManage.jsp">
<img src="image/exit.jpg" width="194" height="37" border="0"></a>
</td></tr>
</table>
</td>
<td>
<table width="100%" height="350" border="1" cellpadding="0" cellspacing="0" bgcolor="#dfeaf1">
<tr><TD align="center" valign="top" style="padding-left:20px;padding-top:10px;">
<div align="left">當前位置: <a href="homepage.jsp">首頁</a> >
<a href="trainManage.jsp">車次資訊管理</a> > 插入車次</div>
<br /><br />
<form action="/TrainDatabase/servlet/InsertTrainAction" method="post">
<table border="1" bordercolor="#12A0F5" align=center>
<tr>
<td>火車車次:</td><td><input type="text" id="trainid"
name="trainid" style='font-size:18px' width=200/></td>
</tr>
<tr>
<td>出發地:</td><td><input type="text" id="start"
name="start" style='font-size:18px' width=200/></td>
</tr>
<tr>
<td>到達地:</td><td><input type="text" id="end"
name="end" style='font-size:18px'/></td>
</tr>
<tr>
<td>行車時間:</td><td><input type="text" id="time"
name="time" style='font-size:18px'/></td>
</tr>
<tr>
<td>硬座票價:</td><td><input type="text" id="yzprice"
name="yzprice" style='font-size:18px'/></td>
</tr>
<tr>
<td>軟座票價:</td><td><input type="text" id="rzprice"
name="rzprice" style='font-size:18px'/></td>
</tr>
<tr>
<td>硬臥票價:</td><td><input type="text" id="ywprice"
name="ywprice" style='font-size:18px'/></td>
</tr>
<tr>
<td>軟臥票價:</td><td><input type="text" id="rwprice"
name="rwprice" style='font-size:18px'/></td>
</tr>
<tr>
<td>車輛路線:</td><td>
<textarea id="root" name="root" rows="5"
style="width:300px;font-size:18px"></textarea>
</td>
</tr>
<tr>
<td colspan=2 align=center><input type="submit"
name="Submit" value="提交" style='font-size:18px' width=200/></td>
</tr>
</table>
</form>
<br /><br />
</TD></tr>
</table>
</td>
</tr>
<tr><td height="20"></td></tr>
</table>
</div>
<div class="div">
<!-- 底部版權所有介面 -->
<TABLE class=wrapper border=0 cellSpacing=0 cellPadding=0 width="100%" align=center>
<TBODY>
<TR><TD style="LINE-HEIGHT: 100%" align="center">
<HR style="WIDTH: 96%; HEIGHT: 4px; COLOR: #02457c">
<font size="2"> <SCRIPT language=javascript src=""></SCRIPT>
<!-- target=_blank開啟新的網頁 -->
<BR><A href="aboutme.jsp">關於我們</A> | <A href="wzsm.jsp"
>網站宣告</A> <BR>版權所有©2014-2015 北京郵電大學 Eastmount<BR>
京ICP備10009636號 </font>
</TD></TR>
</TBODY>
</TABLE>
</div>
</div>
</body>
</html>
該方法不同於前面的,它是通過Servlet實現的。主要是在採用JSP呼叫DAO中插入操作總是失敗,其流程如下:1.點選"插入車次"通過超連結到trainManageInsert.jsp,然後通過表單POST提交到Java檔案servlet;
<form action="/TrainDatabase/servlet/InsertTrainAction" method="post">
2.在InsertTrainAction.java中通過doPost方法獲取提交的表單引數,再呼叫TrainManageDAO.insert(train)插入資料。最後通過response.sendRedirect重定向到管理頁面。
注意:在插入過程中我也是採用"'"+ name +"'"的方式,而不是?來新增引數,否則總報錯,詳見程式碼trainManageDAO.java函式insert(TrainManage train)。
六. 刪除操作
執行效果如下圖所示,點選刪除後彈出提示框“確定”後刪除:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session = "true" %>
<jsp:directive.page import="DAO.TrainManageDAO"/>
<jsp:directive.page import="bean.TrainManage"/>
<jsp:directive.page import="java.util.List"/>
<%
String action = request.getParameter("action");
String id = request.getParameter("id");
if(id == null || id==""){ out.println("沒有選中刪除的車次"); return; }
if("del".equals(action)){
int isDelete = TrainManageDAO.delete(id);
request.setAttribute("isDelete", isDelete);
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>火車卡訂票系統管理系統</title>
</head>
<body>
<div align="center">
<div class="trainCSS">
<table width="1024" height="150" cellpadding="0" cellspacing="0">
<tr><td colspan="2">
<img src="./image/logo.jpg" alt="logo" width="1024" height="149">
</td></tr>
<tr><td width="205" bgcolor="#b7d7ec">
<p align="center">
<script language=JavaScript>
today=new Date();
function initArray(){
this.length=initArray.arguments.length;
for(var i=0;i<this.length;i++)
this[i+1]=initArray.arguments[i]; }
var d=new initArray(
"星期日","星期一","星期二","星期三","星期四", "星期五","星期六");
document.write("<font color=##ff0000 style='font-size:12pt;font-family: 宋體'> ",
today.getYear()+1900,"年",today.getMonth()+1,"月",today.getDate(),"日 ",d[today.getDay()+1],
"</font>" );
</script>
</p>
</td>
<td width="819" bgcolor="#b7d7ec">
<marquee direction="left" onmouseover=this.stop() onmouseout=this.start() scrollAmount=3 scrollDelay=100>
<FONT style="FONT-SIZE: 18px"color=blue>歡迎使用火車票訂票系統管理系統 ,如有不足,敬請指導!</FONT>
</marquee>
</td>
</tr>
<tr><td height="12"></td></tr>
</table>
</div>
<div class="trainCSS">
<table border="0" width="1024" cellpadding="0" cellspacing="0">
<tr><td width="130" bgcolor="#dfeaf1" valign="top">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr><td height="10"></td></tr>
<tr><td align="center"> <font size="3" color="blue">管理員:xxx,歡迎您!</font></td></tr>
<tr><td height="10"></td></tr>
<tr>
<td align="center"><p><a href="trainManage.jsp">
<img src="image/ccxxgl-xz.jpg" width="194" height="37" border="0"></a><td> </td>
</tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="buyManage.jsp">
<img src="image/dpgl.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="peopleManage.jsp">
<img src="image/hygl.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="serverManage.jsp">
<img src="image/spqktj.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="infoManage.jsp">
<img src="image/lygl.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="exitManage.jsp">
<img src="image/exit.jpg" width="194" height="37" border="0"></a>
</td></tr>
</table>
</td>
<td>
<table width="100%" height="350" border="1" cellpadding="0" cellspacing="0" bgcolor="#dfeaf1">
<tr><TD align="center" valign="top" style="padding-left:20px;padding-top:10px;">
<div align="left">當前位置: <a href="homepage.jsp">首頁</a> >
<a href="trainManage.jsp">車次資訊管理</a> > 刪除車次</div>
<br /><br />
<table border="2" bordercolor="#12A0F5" width="50%" height="80%">
<tr align=center>
<td>
<H2 style="COLOR: #880000">刪除成功</H2>
<H4>管理員 xxx 成功刪除該車次資訊<br />系統將在
<input type="text" style='font-size:18px; border:0px; width:20px;'
readonly="true" value="5" id="time">秒後返回火車票系統管理員車次管理介面
</H4>
</td>
</tr>
</table>
<!-- 時間函式 -->
<script language="javascript">
var t = 5;
var time = document.getElementById("time");
function fun()
{
t--;
time.value = t;
if(t<=0)
{
location.href="trainManage.jsp";
}
}
var inter = setInterval("fun()",1000);
</script>
<br /><br />
</TD></tr>
</table>
</td>
</tr>
<tr><td height="20"></td></tr>
</table>
</div>
<div class="div">
<!-- 底部版權所有介面 -->
<TABLE class=wrapper border=0 cellSpacing=0 cellPadding=0 width="100%" align=center>
<TBODY>
<TR><TD style="LINE-HEIGHT: 100%" align="center">
<HR style="WIDTH: 96%; HEIGHT: 4px; COLOR: #02457c">
<font size="2"> <SCRIPT language=javascript src=""></SCRIPT>
<!-- target=_blank開啟新的網頁 -->
<BR><A href="aboutme.jsp">關於我們</A> | <A href="wzsm.jsp"
>網站宣告</A> <BR>版權所有©2014-2015 北京郵電大學 Eastmount <BR>
京ICP備10009636號 </font>
</TD></TR>
</TBODY>
</TABLE>
</div>
</div>
</body>
</html>
刪除的核心程式碼如下:1.在trainManage.jsp中定義刪除超連結及提示框:
<a href="trainManageDelete.jsp?action=del&id=${train.trainid}"
onclick="return confirm('確定刪除?')">刪除</a>
2.在DAO中trainManageDAO.java檔案中定義SQL刪除操作:
public static int delete(String id) throws Exception {
String sql = "DELETE FROM TrainManage WHERE trainid = ? ";
return JDBCConnect.executeUpdate(sql, id);
}
3.在trainManageDelete.jsp中獲取傳遞的trainid(火車車次)值並呼叫該函式實現刪除操作:
<%
String action = request.getParameter("action");
String id = request.getParameter("id");
if(id == null || id==""){out.println("沒有選中刪除的車次");return;}
if("del".equals(action)){
int isDelete = TrainManageDAO.delete(id);
request.setAttribute("isDelete", isDelete);
}
%>
七. 更新操作及Servlet
具體流程是:首先點選修改,通過超鏈傳遞trainid(火車車次)到修改介面,然後通過呼叫trainManageDAO.java中find查詢該車次的所有資訊並顯示。再通過提交POST及Servlet到UpdateTrainAction.java中,在doPost方法中呼叫DAO中update(TrainMManage)實現更新。其中執行結果如下圖所示:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session = "true" %>
<jsp:directive.page import="DAO.TrainManageDAO"/>
<jsp:directive.page import="bean.TrainManage"/>
<jsp:directive.page import="java.util.List"/>
<%
String action = request.getParameter("action");
String id = request.getParameter("id");
TrainManage train = TrainManageDAO.find(id);
request.setAttribute("train", train);
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>火車卡訂票系統管理系統</title>
</head>
<body>
<div align="center">
<div class="trainCSS">
<table width="1024" height="150" cellpadding="0" cellspacing="0">
<tr><td colspan="2">
<img src="./image/logo.jpg" alt="logo" width="1024" height="149">
</td></tr>
<tr><td width="205" bgcolor="#b7d7ec">
<p align="center">
<script language=JavaScript>
today=new Date();
function initArray(){
this.length=initArray.arguments.length;
for(var i=0;i<this.length;i++)
this[i+1]=initArray.arguments[i]; }
var d=new initArray(
"星期日","星期一","星期二","星期三","星期四", "星期五","星期六");
document.write("<font color=##ff0000 style='font-size:12pt;font-family: 宋體'> ",
today.getYear()+1900,"年",today.getMonth()+1,"月",today.getDate(),"日 ",d[today.getDay()+1],
"</font>" );
</script>
</p>
</td>
<td width="819" bgcolor="#b7d7ec">
<marquee direction="left" onmouseover=this.stop() onmouseout=this.start() scrollAmount=3 scrollDelay=100>
<FONT style="FONT-SIZE: 18px"color=blue>歡迎使用火車票訂票系統管理系統 ,如有不足,敬請指導!</FONT>
</marquee>
</td>
</tr>
<tr><td height="12"></td></tr>
</table>
</div>
<div class="trainCSS">
<table border="0" width="1024" cellpadding="0" cellspacing="0">
<tr><td width="130" bgcolor="#dfeaf1" valign="top">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr><td height="10"></td></tr>
<tr><td align="center"> <font size="3" color="blue">管理員:xxx,歡迎您!</font></td></tr>
<tr><td height="10"></td></tr>
<tr>
<td align="center"><p><a href="trainManage.jsp">
<img src="image/ccxxgl-xz.jpg" width="194" height="37" border="0"></a><td> </td>
</tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="buyManage.jsp">
<img src="image/dpgl.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="peopleManage.jsp">
<img src="image/hygl.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="serverManage.jsp">
<img src="image/spqktj.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="infoManage.jsp">
<img src="image/lygl.jpg" width="194" height="37" border="0"></a>
</td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center"><a href="exitManage.jsp">
<img src="image/exit.jpg" width="194" height="37" border="0"></a>
</td></tr>
</table>
</td>
<td>
<table width="100%" height="350" border="1" cellpadding="0" cellspacing="0" bgcolor="#dfeaf1">
<tr><TD align="center" valign="top" style="padding-left:20px;padding-top:10px;">
<div align="left">當前位置: <a href="homepage.jsp">首頁</a> > <a href="trainManage.jsp">車次資訊管理</a> > 插入車次</div>
<br /><br />
<H2 style="COLOR: #880000">修改車次資訊</H2>
<form action="/TrainDatabase/servlet/UpdateTrainAction" method="post">
<table border="1" bordercolor="#12A0F5" align=center>
<tr>
<td>火車車次:</td><td><input type="text" id="trainid" name="trainid"
value=${train.trainid} style='font-size:18px' width=200 readonly="true""/></td>
</tr>
<tr>
<td>出發地:</td><td><input type="text" id="start" name="start"
value=${train.start} style='font-size:18px' width=200/></td>
</tr>
<tr>
<td>到達地:</td><td><input type="text" id="end" name="end"
value=${train.end} style='font-size:18px'/></td>
</tr>
<tr>
<td>行車時間:</td><td><input type="text" id="time" name="time"
value=${train.time} style='font-size:18px'/></td>
</tr>
<tr>
<td>硬座票價:</td><td><input type="text" id="yzprice" name="yzprice"
value=${train.yzprice} style='font-size:18px'/></td>
</tr>
<tr>
<td>軟座票價:</td><td><input type="text" id="rzprice" name="rzprice"
value=${train.rzprice} style='font-size:18px'/></td>
</tr>
<tr>
<td>硬臥票價:</td><td><input type="text" id="ywprice" name="ywprice"
value=${train.ywprice} style='font-size:18px'/></td>
</tr>
<tr>
<td>軟臥票價:</td><td><input type="text" id="rwprice" name="rwprice"
value=${train.rwprice} style='font-size:18px'/></td>
</tr>
<tr>
<td>車輛路線:</td><td>
<textarea id="root" name="root" rows="5"
style="width:300px;font-size:18px">${train.root}</textarea>
</td>
</tr>
<tr>
<td colspan=2 align=center><input type="submit" name="Submit"
value="提交" style='font-size:18px' width=200/></td>
</tr>
</table>
</form>
<br /><br />
</TD></tr>
</table>
</td>
</tr>
<tr><td height="20"></td></tr>
</table>
</div>
<div class="div">
<!-- 底部版權所有介面 -->
<TABLE class=wrapper border=0 cellSpacing=0 cellPadding=0 width="100%" align=center>
<TBODY>
<TR><TD style="LINE-HEIGHT: 100%" align="center">
<HR style="WIDTH: 96%; HEIGHT: 4px; COLOR: #02457c">
<font size="2"> <SCRIPT language=javascript src=""></SCRIPT>
<!-- target=_blank開啟新的網頁 -->
<BR><A href="aboutme.jsp">關於我們</A> | <A href="wzsm.jsp"
>網站宣告</A> <BR>版權所有©2014-2015 北京郵電大學 Eastmount <BR>
京ICP備10009636號 </font>
</TD></TR>
</TBODY>
</TABLE>
</div>
</div>
</body>
</html>
然後再src/servlet中建立Servlet類,即UpdateTrainAction.java檔案。程式碼如下:package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import DAO.TrainManageDAO;
import bean.TrainManage;
public class UpdateTrainAction extends HttpServlet {
public UpdateTrainAction() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
//The doGet method of the servlet.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
//The doPost method of the servlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8"); //設定輸出編碼
request.setCharacterEncoding("UTF-8");
try {
//更新資料庫
String m_trainid = request.getParameter("trainid");
String m_start = request.getParameter("start");
String m_end = request.getParameter("end");
String m_time = request.getParameter("time");
String m_yz = request.getParameter("yzprice");
Float m_yzprice = Float.parseFloat(m_yz);
String m_rz = request.getParameter("rzprice");
Float m_rzprice = Float.parseFloat(m_rz);
String m_yw = request.getParameter("ywprice");
Float m_ywprice = Float.parseFloat(m_yw);
String m_rw = request.getParameter("rwprice");
Float m_rwprice = Float.parseFloat(m_rw);
String m_root = request.getParameter("root");
TrainManage train = new TrainManage();
train.setTrainid(m_trainid);
train.setStart(m_start);
train.setEnd(m_end);
train.setTime(m_time);
train.setYzprice(m_yzprice);
train.setRzprice(m_rzprice);
train.setYwprice(m_ywprice);
train.setRwprice(m_rwprice);
train.setRoot(m_root);
int success = TrainManageDAO.update(train);
request.setAttribute("success", success);
//設定全路徑 否則trainManage.jsp跳轉到servlet/trainManage.jsp路徑下不存在
response.sendRedirect("http://localhost:8080/TrainDatabase/trainManage.jsp");
} catch(Exception e) {
System.out.println("錯誤:"+e.getMessage());
response.sendRedirect("http://localhost:8080/TrainDatabase/trainManage.jsp");
}
}
public void init() throws ServletException {
// Put your code here
}
}
你可能發現,update函式只修改了start和end,其它你可以自己新增,方法類似。同時如果引數過多建議使用下面的方法替代:public static int update(TrainManage train) throws Exception {
/**
* String sql = "UPDATE TrainManage SET start = ?, end = ? WHERE trainid = ? ";
* return JDBCConnect.executeUpdate(sql, train.getStart(), train.getEnd(), train.getTrainid());
*/
String sql = "UPDATE TrainManage SET start = '"+ train.getStart() +
"', end = '" + train.getEnd() + "' WHERE trainid = '" + train.getTrainid() +"';";
System.out.println(sql);
return JDBCConnect.executeUpdate(sql);
}
還有一個檢視詳情就不介紹了,參看原始碼吧~八. 總結
最後文章就不總結了,因為每步都講得非常清楚,無論是步驟、思想,還是原始碼截圖。作者真的很用心的寫這篇文章,從晚上8點寫到了凌晨5點,中間打了兩把dota2。一方面由於我也認為這些都非常重要又基礎,另一方面為哪些初學者做Java網站的。
最後希望文章對你有所幫助!如果文章有錯誤或不足之處,還請海涵~真的有點累了睡了。有時候想想值不值得這樣寫文章,心安雖好但對身體不好。
相關文章
- JSP實現servlet對資料庫的增刪查改操作JSServlet資料庫
- 資料庫操作增刪改查模糊查資料庫
- C# 資料操作系列 - 15 SqlSugar 增刪改查詳解C#SqlSugar
- YII1 增、刪、改、查資料庫操作資料庫
- Python操作SQLServer資料庫增刪改查PythonSQLServer資料庫
- mysql資料增刪改查操作MySql
- Golang原生sql操作Mysql資料庫增刪改查GolangMySql資料庫
- 基本的資料庫增刪改查資料庫
- 資料庫的簡介和MySQL增刪改查資料庫MySql
- Java+MyEclipse+Tomcat (四)Servlet提交表單和資料庫操作JavaEclipseTomcatServlet資料庫
- JavaScript表格增刪改查詳解JavaScript
- Flutter資料庫Sqflite之增刪改查Flutter資料庫
- mogoose 建立資料庫並增刪改查Go資料庫
- go——beego的資料庫增刪改查Go資料庫
- MongoDB增刪改查操作MongoDB
- Mybatis 學習筆記(二)——原生DAO實現資料增刪改查MyBatis筆記
- 關於mongodb資料庫的增刪改查MongoDB資料庫
- 搭建頁面:資料庫的增刪改查資料庫
- iOS FMDB資料庫之增刪改查使用iOS資料庫
- 使用Chatgpt編寫的PHP資料庫pdo操作類(增刪改查)ChatGPTPHP資料庫
- PHP操作MongoDB(增刪改查)PHPMongoDB
- Java+MyEclipse+Tomcat (五)DAO和Java Bean實現資料庫和介面分開操作JavaEclipseTomcatBean資料庫
- MongoDB 資料庫建立刪除、表(集合)建立刪除、資料增刪改查MongoDB資料庫
- mybatis實現MySQL資料庫的增刪改查MyBatisMySql資料庫
- 連線資料庫並實現增、刪、改、查資料庫
- 自寫的使用PDO對mysql資料庫的增刪改查操作類MySql資料庫
- MySQL基礎操作(增刪改查)MySql
- JS字串操作之增刪改查JS字串
- angualrJs對資料庫資料處理的增刪改查JS資料庫
- Oracle、mysql資料庫增、刪、改OracleMySql資料庫
- C# 資料操作系列 - 12 NHibernate的增刪改查C#
- MySql 表資料的增、刪、改、查MySql
- MySQL資料庫 ---MySQL表的增刪改查(進階)MySql資料庫
- 用jsp實現資料庫的增刪改查JS資料庫
- SQL Server 表的管理_關於資料增刪查改的操作的詳解(案例程式碼)SQLServer
- jquery基本操作增刪改查有哪些?jQuery
- JavaAPI操作MongoDB--基本增刪改查JavaAPIMongoDB
- MyBatis框架搭建及增刪改查操作MyBatis框架