使用Servlet做一個(gè)單表的CRUD操作
開(kāi)發(fā)前的準(zhǔn)備
導(dǎo)入sql腳本創(chuàng)建一張部門表
drop table if exists dept;
create table dept(
deptno int primary key,
dname varchar(255),
loc varchar(255)
);
insert into dept(deptno, dname, loc) values(10, 'XiaoShouBu', 'BeiJing');
insert into dept(deptno, dname, loc) values(20, 'YanFaBu', 'SHANGHAI');
insert into dept(deptno, dname, loc) values(30, 'JiShuBu', 'GUANGZHOU');
insert into dept(deptno, dname, loc) values(40, 'MeiTiBu', 'SHENZHEN');
commit;
select * from dept;
通過(guò)綁定屬性資源配置文件的方式創(chuàng)建JDBC的工具類utils/DBUtil
#在src類路徑下新建包resourcse,在包中新建一個(gè)屬性配置文件jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/javaweb
user=root
password=123456
public class DBUtil {
// 綁定屬性資源配置文件,配置文件的后綴名不用寫,文件路徑路徑分隔符可以是"."也可以是"/"
private static ResourceBundle bundle = ResourceBundle.getBundle("resources.jdbc");
// 根據(jù)屬性配置文件的key獲取value,靜態(tài)變量在類加載時(shí)按自上而下的順序執(zhí)行
private static String driver = bundle.getString("driver");
private static String url = bundle.getString("url");
private static String user = bundle.getString("user");
private static String password = bundle.getString("password");
static {
// 由于注冊(cè)驅(qū)動(dòng)只需要注冊(cè)一次所以可以放在靜態(tài)代碼塊當(dāng)中,當(dāng)DBUtil類加載的時(shí)候執(zhí)行靜態(tài)代碼塊中的代碼
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 獲取數(shù)據(jù)庫(kù)連接對(duì)象
* @return conn 連接對(duì)象
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
// 獲取連接
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
/**
* 釋放資源
* @param conn 連接對(duì)象
* @param ps 數(shù)據(jù)庫(kù)操作對(duì)象
* @param rs 結(jié)果集對(duì)象
*/
public static void close(Connection conn, Statement ps, ResultSet rs){
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
實(shí)現(xiàn)系統(tǒng)功能
分析系統(tǒng)的功能: 只要這個(gè)操作連接了數(shù)據(jù)庫(kù),就表示一個(gè)獨(dú)立的功能
- 查看部門列表 , 新增部門 , 刪除部門 , 查看部門詳細(xì)信息 , 跳轉(zhuǎn)到修改頁(yè)面(動(dòng)態(tài)的從數(shù)據(jù)庫(kù)中獲取信息并顯示) , 修改部門
實(shí)現(xiàn)一個(gè)具體功能: 可以從后端往前端一步一步寫, 以可以從前端一步一步往后端寫 , 千萬(wàn)不要想起來(lái)什么寫什么
- 假設(shè)從前端開(kāi)始,那么一定是從用戶點(diǎn)擊按鈕那里開(kāi)始的—>用戶點(diǎn)擊的東西在哪里–>用戶點(diǎn)擊的按鈕時(shí)具體發(fā)起什么請(qǐng)求
實(shí)現(xiàn)查看部門列表功能
設(shè)置歡迎頁(yè)面index.html的超鏈接,用戶通過(guò)點(diǎn)擊"查看部門列表按鈕"跳轉(zhuǎn)到部門列表頁(yè)面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>歡迎使用OA系統(tǒng)</title>
</head>
<body>
<!--前端超鏈接發(fā)送請(qǐng)求的時(shí)候,請(qǐng)求路徑以“/”開(kāi)始,并且要帶著項(xiàng)目名-->
<a href="/oa/dept/list">查看部門列表</a>
</body>
</html>
編寫DeptListServlet類繼承HttpServlet類并重寫doGet方法(配置到web.xml文件中)
- 在DeptListServlet類的doGet方法中連接數(shù)據(jù)查詢所有的部門,分析部門列表頁(yè)面中哪部分是固定死的,哪部分是需要?jiǎng)討B(tài)展示數(shù)據(jù)的
- 部門列表頁(yè)面中的內(nèi)容所有的雙引號(hào)要替換成單引號(hào),因?yàn)閛ut.print(“”)這里有一個(gè)雙引號(hào)容易沖突 (可以利用文本工具查找替換)
<servlet>
<servlet-name>list</servlet-name>
<servlet-class>com.bjpowernode.oa.web.action.DeptListServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>list</servlet-name>
<!--web.xml文件中的這個(gè)路徑也是以“/”開(kāi)始的,但是不需要加項(xiàng)目名-->
<url-pattern>/dept/list</url-pattern>
</servlet-mapping>
public class DeptListServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 獲取應(yīng)用的根路徑
String contextPath = request.getContextPath();
// 設(shè)置響應(yīng)的內(nèi)容類型以及字符集,防止中文亂碼問(wèn)題
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// 使用多行編輯功能 , 按住Alt鍵 , 鼠標(biāo)往下托就行
out.print("<!DOCTYPE html>");
out.print("<html>");
out.print(" <head>");
out.print(" <meta charset='utf-8'>");
out.print(" <title>部門列表頁(yè)面</title>");
//刪除按鈕執(zhí)行的事件函數(shù)
out.print("<script type='text/javascript'>");
out.print(" function del(dno){");
out.print(" if(window.confirm('親,刪了不可恢復(fù)哦!')){");
out.print(" document.location.href = '"+contextPath+"/dept/delete?deptno=' + dno");
out.print(" }");
out.print(" }");
out.print("</script>");
out.print(" </head>");
out.print(" <body>");
out.print(" <h1 align='center'>部門列表</h1>");
out.print(" <hr >");
out.print(" <table border='1px' align='center' width='50%'>");
out.print(" <tr>");
out.print(" <th>序號(hào)</th>");
out.print(" <th>部門編號(hào)</th>");
out.print(" <th>部門名稱</th>");
out.print(" <th>操作</th>");
out.print(" </tr>");
/*上面一部分是死的*/
// 動(dòng)態(tài)的連接數(shù)據(jù)庫(kù),查詢所有的部門
//...................
/*下面一部分是死的*/
out.print(" </table>");
out.print(" <hr >");
out.print(" <a href='"+contextPath+"/add.html'>新增部門</a>");
out.print(" </body>");
out.print("</html>");
}
}
動(dòng)態(tài)的連接數(shù)據(jù)庫(kù)查詢所有的部門
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 獲取連接
conn = DBUtil.getConnection();
// 獲取預(yù)編譯的數(shù)據(jù)庫(kù)操作對(duì)象
String sql = "select deptno as a,dname,loc from dept";
ps = conn.prepareStatement(sql);
// 執(zhí)行SQL語(yǔ)句
rs = ps.executeQuery();
// 處理結(jié)果集
// i 表示序號(hào)
int i = 0;
while(rs.next()){
String deptno = rs.getString("a");
String dname = rs.getString("dname");
String loc = rs.getString("loc");
out.print(" <tr>");
out.print(" <td>"+(++i)+"</td>");
out.print(" <td>"+deptno+"</td>");
out.print(" <td>"+dname+"</td>");
out.print(" <td>");
//點(diǎn)擊按鈕不會(huì)進(jìn)行頁(yè)面的跳轉(zhuǎn),而是執(zhí)行事件函數(shù)
out.print(" <a href='javascript:void(0)' οnclick='del("+deptno+")'>刪除</a>");
out.print(" <a href='"+contextPath+"/dept/edit?deptno="+deptno+"'>修改</a>");
out.print(" <a href='"+contextPath+"/dept/detail?deptno="+deptno+"'>詳情</a>");
out.print(" </td>");
out.print(" </tr>");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 釋放資源
DBUtil.close(conn, ps, rs);
}
實(shí)現(xiàn)查看部門詳情功能
用戶點(diǎn)的“詳情”的按鈕是DeptListServlet 動(dòng)態(tài)的響應(yīng)的內(nèi)容,后端連接數(shù)據(jù)庫(kù)查詢部門信息時(shí),不同的部門對(duì)應(yīng)不同的編號(hào),同理請(qǐng)求參數(shù)deptno的值也不同
- 這個(gè)超鏈接路徑是需要加項(xiàng)目名的, 并且請(qǐng)求參數(shù)中需要攜帶你想要查看的部門編號(hào) , 這樣才能連接數(shù)據(jù)庫(kù)查詢對(duì)應(yīng)部門信息
while(rs.next()){
String deptno = rs.getString("a");
// 部分代碼省略
// 向服務(wù)器提交數(shù)據(jù)的格式:uri?name=value&name=value&...
out.print(" <a href='"+contextPath+"/dept/detail?deptno="+deptno+"'>詳情</a>");
}
編寫DeptDetailServlet繼承HttpServlet并重寫doGet方法((配置到web.xml文件中)
- 在doGet方法當(dāng)中根據(jù)獲取的部門編號(hào)連接數(shù)據(jù)庫(kù)查詢對(duì)應(yīng)部門的信息, 并動(dòng)態(tài)的將部門詳情頁(yè)展示到瀏覽器上
<servlet>
<servlet-name>detail</servlet-name>
<servlet-class>com.bjpowernode.oa.web.action.DeptDetailServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>detail</servlet-name>
<url-pattern>/dept/detail</url-pattern>
</servlet-mapping>
public class DeptDetailServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("<!DOCTYPE html>");
out.print("<html>");
out.print(" <head>");
out.print(" <meta charset='utf-8'>");
out.print(" <title>部門詳情</title>");
out.print(" </head>");
out.print(" <body>");
out.print(" <h1>部門詳情</h1>");
out.print(" <hr >");
/*上面一部分是死的*/
// 根據(jù)部門編號(hào)連接數(shù)據(jù)庫(kù)查詢對(duì)應(yīng)部門的信息并動(dòng)態(tài)展示
//...................
/*下面一部分是死的*/
out.print(" <input type='button' value='后退' οnclick='window.history.back()'/>");
out.print(" </body>");
out.print("</html>");
}
}
從請(qǐng)求地址[/oa/dept/detail?deptno=30][]中uri中的請(qǐng)求參數(shù)獲取部門編號(hào)然后連接數(shù)據(jù)庫(kù)查詢?cè)摬块T的信息,最后動(dòng)態(tài)展示部門詳情頁(yè)的代碼
// 雖然瀏覽器提交的是30這個(gè)數(shù)字,但是服務(wù)器獲取的是"30"字符串
String deptno = request.getParameter("deptno");
// 連接數(shù)據(jù)庫(kù)根據(jù)部門編號(hào)查詢部門信息
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
// mysql底層自動(dòng)會(huì)把"30"轉(zhuǎn)換成30
String sql = "select dname,loc from dept where deptno = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, deptno);
rs = ps.executeQuery();
// 這個(gè)結(jié)果集一定只有一條記錄
if(rs.next()){
String dname = rs.getString("dname");
String loc = rs.getString("loc");
out.print("部門編號(hào):"+deptno+" <br>");
out.print("部門名稱:"+dname+"<br>");
out.print("部門位置:"+loc+"<br>");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(conn, ps, rs);
}
實(shí)現(xiàn)刪除部門功能
用戶點(diǎn)的“刪除”按鈕是DeptListServlet 動(dòng)態(tài)響應(yīng)的內(nèi)容 ,點(diǎn)擊刪除按鈕要執(zhí)行的事件函數(shù)也是DeptListServlet動(dòng)態(tài)的響應(yīng)的內(nèi)容
- 刪除這個(gè)動(dòng)作是比較危險(xiǎn)的,所以一般通過(guò)點(diǎn)擊超鏈接后先執(zhí)行事件函數(shù)不跳轉(zhuǎn)頁(yè)面, 在事件函數(shù)中發(fā)起請(qǐng)求實(shí)現(xiàn)刪除部門的功能
- 后端連接數(shù)據(jù)庫(kù)查詢部門信息時(shí), 不同的部門對(duì)應(yīng)不同的編號(hào),同理請(qǐng)求參數(shù)deptno的值也不同
- 刪除部門對(duì)應(yīng)兩種結(jié)果成功或者失敗,成功如何處理,失敗又如何處理
while(rs.next()){
// 部分代碼省略
String deptno = rs.getString("a");
// href設(shè)置為javascript:void(0)或javascript:;都會(huì)保留超鏈接的樣子,但是點(diǎn)擊后不進(jìn)行頁(yè)面的跳轉(zhuǎn)
out.print(" <a href='javascript:void(0)' οnclick='del("+deptno+")'>刪除</a>");
}
// 根據(jù)部門編號(hào)刪除對(duì)應(yīng)的部門
out.print("<script type='text/javascript'>");
out.print(" function del(dno){");
out.print(" if(window.confirm('親,刪了不可恢復(fù)哦!')){");
// 跳轉(zhuǎn)頁(yè)面的幾種方式: document.location = "請(qǐng)求路徑"(document都可以替換成window)
out.print(" document.location.href = '"+contextPath+"/dept/delete?deptno=' + dno");
out.print(" }");
out.print(" }");
out.print("</script>");
編寫DeptDelServlet繼承HttpServlet并重寫doGet方法(配置到web.xml文件中)
- 在doGet方法當(dāng)中根據(jù)部門編號(hào)刪除對(duì)應(yīng)的部門,刪除成功后再重定向到部門列表頁(yè)面(Servlet)
<servlet>
<servlet-name>delete</servlet-name>
<servlet-class>com.bjpowernode.oa.web.action.DeptDelServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>delete</servlet-name>
<url-pattern>/dept/delete</url-pattern>
</servlet-mapping>
public class DeptDelServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 根據(jù)請(qǐng)求參數(shù)獲取的部門編號(hào)連接數(shù)據(jù)庫(kù)刪除對(duì)應(yīng)部門記錄
String deptno = request.getParameter("deptno");
Connection conn = null;
PreparedStatement ps = null;
// count判斷判斷刪除成功了還是失敗了
int count = 0;
try {
conn = DBUtil.getConnection();
// 開(kāi)啟事務(wù)(自動(dòng)提交機(jī)制關(guān)閉)
conn.setAutoCommit(false);
String sql = "delete from dept where deptno = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, deptno);
// 返回值是影響了數(shù)據(jù)庫(kù)表當(dāng)中多少條記錄
count = ps.executeUpdate();
// 事務(wù)提交
conn.commit();
} catch (SQLException e) {
// 遇到異常要回滾
if (conn != null) {
try {
conn.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
e.printStackTrace();
} finally {
DBUtil.close(conn, ps, null);
}
// 判斷刪除成功了還是失敗了..........
}
}
刪除成功或者失敗的時(shí)候的一個(gè)處理 , 因?yàn)椴恍枰蚕頂?shù)據(jù)所以我們使用重定向機(jī)制
- 刪除成功重定向到部門列表頁(yè)面即執(zhí)行DeptListServlet
- 刪除失敗重定向到error.html頁(yè)面
if (count == 1) { //刪除成功
response.sendRedirect(request.getContextPath() + "/dept/list");
}else{ // 刪除失敗
response.sendRedirect(request.getContextPath() + "/error.html");
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>error</title>
</head>
<body>
<h1>操作失敗,<a href="javascript:void(0)" onclick="window.history.back()">返回</a></h1>
</body>
</html>
實(shí)現(xiàn)新增部門功能
“新增部門”的按鈕在DeptListServlet動(dòng)態(tài)響應(yīng)的內(nèi)容中, 通過(guò)點(diǎn)擊該鏈接直接跳轉(zhuǎn)到新增部門的表單頁(yè)面,利用表單發(fā)起post請(qǐng)求提交新增部門的信息
/*下面一部分是死的*/
out.print(" <a href='"+contextPath+"/add.html'>新增部門</a>");
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>新增部門</title>
</head>
<body>
<h1>新增部門</h1>
<hr >
<!--發(fā)起post請(qǐng)求,新增部門-->
<form action="/oa/dept/save" method="post">
部門編號(hào)<input type="text" name="deptno"/><br>
部門名稱<input type="text" name="dname"/><br>
部門位置<input type="text" name="loc"/><br>
<input type="submit" value="保存"/><br>
</form>
</body>
</html>
編寫DeptSaveServlet繼承HttpServlet并重寫doPost方法(配置到web.xml文件中)
- 在doPost方法當(dāng)中連接數(shù)據(jù)庫(kù)保存新增的部門信息,新增部門成功后重定向到部門列表頁(yè)面(如果轉(zhuǎn)發(fā)轉(zhuǎn)發(fā)的是post請(qǐng)求需要執(zhí)行doPost方法)
- 保存新增部門信息時(shí)可能保存成功也可能保存失敗,保存成功如何處理,失敗后又如何處理
<servlet>
<servlet-name>save</servlet-name>
<servlet-class>com.bjpowernode.oa.web.action.DeptSaveServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>save</servlet-name>
<url-pattern>/dept/save</url-pattern>
</servlet-mapping>
public class DeptSaveServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 獲取部門的信息時(shí)注意亂碼問(wèn)題(Tomcat10不會(huì)出現(xiàn)這個(gè)問(wèn)題)
request.setCharacterEncoding("UTF-8");
String deptno = request.getParameter("deptno");
String dname = request.getParameter("dname");
String loc = request.getParameter("loc");
// 連接數(shù)據(jù)庫(kù)執(zhí)行insert語(yǔ)句
Connection conn = null;
PreparedStatement ps = null;
// 判斷保存成功還是失敗
int count = 0;
try {
conn = DBUtil.getConnection();
String sql = "insert into dept(deptno, dname, loc) values(?,?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1, deptno);
ps.setString(2, dname);
ps.setString(3, loc);
count = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(conn, ps, null);
}
// 判斷保存成功還是失敗 , 保存成功跳轉(zhuǎn)到列表頁(yè)面.................
}
}
轉(zhuǎn)發(fā)到/dept/list會(huì)出現(xiàn)405錯(cuò)誤, 由于轉(zhuǎn)發(fā)是一次請(qǐng)求, 保存新增部門信息表單發(fā)起的是post請(qǐng)求, 轉(zhuǎn)發(fā)到DeptListServlet時(shí)需要調(diào)用doPost方法處理請(qǐng)求
public class DeptListServlet extends HttpServlet {
// 處理post請(qǐng)求然后在doPost方法中調(diào)用doGet方法
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 連接數(shù)據(jù)庫(kù),動(dòng)態(tài)展示部門列表頁(yè)面
}
重定向到/oa/dept/list, 瀏覽器此時(shí)會(huì)在地址欄上發(fā)起一次全新的get請(qǐng)求,調(diào)用DeptListServlet的doGet方法處理請(qǐng)求
if (count == 1) {//新增成功
// 顯示部門列表頁(yè)面
response.sendRedirect(request.getContextPath() + "/dept/list");
}else{// 新增失敗
// 使用重定向跳轉(zhuǎn)到錯(cuò)誤頁(yè)面
response.sendRedirect(request.getContextPath() + "/error.html");
}
實(shí)現(xiàn)查看部門詳情可修改功能
用戶點(diǎn)擊的“修改”按鈕是DeptListServlet動(dòng)態(tài)響應(yīng)的內(nèi)容,后端連接數(shù)據(jù)庫(kù)查詢部門信息時(shí),不同的部門對(duì)應(yīng)不同的編號(hào),同理請(qǐng)求參數(shù)deptno的值也不同
- 這個(gè)路徑是需要加項(xiàng)目名的, 請(qǐng)求參數(shù)攜帶你想要查看的部門編號(hào) , 這樣才能連接數(shù)據(jù)庫(kù)查詢部門信息動(dòng)態(tài)的輸出要修改的部門信息
while(rs.next()){
String deptno = rs.getString("a");
out.print(" <a href='"+contextPath+"/dept/edit?deptno="+deptno+"'>修改</a>");
}
編寫DeptEditServlet繼承HttpServlet并重寫doGet方法(配置到web.xml文件中)
- 在doGet方法中根據(jù)請(qǐng)求參數(shù)中獲取的部門編號(hào)連接數(shù)據(jù)庫(kù)查詢對(duì)應(yīng)部門的信息并以表單的形式展示數(shù)據(jù)
<servlet>
<servlet-name>edit</servlet-name>
<servlet-class>com.bjpowernode.oa.web.action.DeptEditServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>edit</servlet-name>
<url-pattern>/dept/edit</url-pattern>
</servlet-mapping>
public class DeptEditServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 獲取應(yīng)用的根路徑
String contextPath = request.getContextPath();
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("<!DOCTYPE html>");
out.print("<html>");
out.print(" <head>");
out.print(" <meta charset='utf-8'>");
out.print(" <title>修改部門</title>");
out.print(" </head>");
out.print(" <body>");
out.print(" <h1>修改部門</h1>");
out.print(" <hr >");
// 利用表單發(fā)起請(qǐng)求,保存部門修改后的信息
out.print(" <form action='"+contextPath+"/dept/modify' method='post'>");
//上面一部分是死的
// 連接數(shù)據(jù)庫(kù),動(dòng)態(tài)輸出部門的信息.....
。
//下面一部分是死的
out.print(" <input type='submit' value='修改'/><br>");
out.print(" </form>");
out.print(" </body>");
out.print("</html>");
}
}
根據(jù)請(qǐng)求參數(shù)中攜帶的部門編號(hào)連接數(shù)據(jù)庫(kù),動(dòng)態(tài)的將查詢到的部門信息保存到一個(gè)表單中并返回給瀏覽器(這里的部門編號(hào)是只讀的,readonly屬性)
// 獲取請(qǐng)求參數(shù)中攜帶的部門編號(hào)
String deptno = request.getParameter("deptno");
// 根據(jù)部門編號(hào)連接數(shù)據(jù)庫(kù)查詢部門信息
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
String sql = "select dname, loc as location from dept where deptno = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, deptno);
rs = ps.executeQuery();
// 這個(gè)結(jié)果集中只有一條記錄
if(rs.next()){
String dname = rs.getString("dname");
// 參數(shù)"location"是sql語(yǔ)句查詢結(jié)果列的列名
String location = rs.getString("location");
// 部門編號(hào)是只讀的
out.print(" 部門編號(hào)<input type='text' name='deptno' value='"+deptno+"' readonly /><br>");
out.print(" 部門名稱<input type='text' name='dname' value='"+dname+"'/><br>");
out.print(" 部門位置<input type='text' name='loc' value='"+location+"'/><br>");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(conn, ps, rs);
}
實(shí)現(xiàn)修改部門功能
用戶點(diǎn)擊的“修改”按鈕是DeptEditServlet動(dòng)態(tài)響應(yīng)的內(nèi)容,這個(gè)路徑是需要加項(xiàng)目名的, 表單的name作為請(qǐng)求參數(shù),表單的值作為value
// 利用表單發(fā)起請(qǐng)求,保存部門修改后的信息
out.print(" <form action='"+contextPath+"/dept/modify' method='post'>");
//下面一部分是死的
out.print(" <input type='submit' value='修改'/><br>");
out.print(" </form>");
編寫DeptModifyServlet類繼承HttpServlet并重寫doPost方法(配置到web.xml文件中)
- 在doPost方法當(dāng)中連接數(shù)據(jù)庫(kù)完成部門信息的更新 , 數(shù)據(jù)庫(kù)更新成功后需要重定向到部門列表頁(yè)面(Servlet)
- 更新部門信息時(shí)可能更新成功也可能更新失敗,更新成功如何處理,更新失敗后又如何處理
<servlet>
<servlet-name>modify</servlet-name>
<servlet-class>com.bjpowernode.oa.web.action.DeptModifyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>modify</servlet-name>
<url-pattern>/dept/modify</url-pattern>
</servlet-mapping>
public class DeptModifyServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 解決請(qǐng)求體的中文亂碼問(wèn)題
request.setCharacterEncoding("UTF-8");
// 獲取表單中的數(shù)據(jù)
String deptno = request.getParameter("deptno");
String dname = request.getParameter("dname");
String loc = request.getParameter("loc");
// 連接數(shù)據(jù)庫(kù)執(zhí)行更新語(yǔ)句
Connection conn = null;
PreparedStatement ps = null;
// 判斷更新成功或者失敗
int count = 0;
try {
conn = DBUtil.getConnection();
String sql = "update dept set dname = ?, loc = ? where deptno = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, dname);
ps.setString(2, loc);
ps.setString(3, deptno);
count = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(conn, ps, null);
}
//更新部門信息成功或者失敗的一個(gè)處理.....
}
}
更新部門信息成功或者失敗的一個(gè)處理, 如果不需要共享數(shù)據(jù),頁(yè)面跳轉(zhuǎn)都是以重定向
if (count == 1) { // 更新成功
// 重定向到部門列表頁(yè)面(部門列表頁(yè)面是通過(guò)Java程序動(dòng)態(tài)生成的,所以還需要再次執(zhí)行另一個(gè)Servlet)
response.sendRedirect(request.getContextPath() + "/dept/list");
}else{ // 更新失敗
response.sendRedirect(request.getContextPath() + "/error.html");
}
使用模板方法設(shè)計(jì)模式優(yōu)化oa項(xiàng)目
模板方法設(shè)計(jì)模式解決類爆炸
如果每一個(gè)請(qǐng)求都對(duì)應(yīng)一個(gè)Servlet類就會(huì)導(dǎo)致類爆炸 , 一般一個(gè)請(qǐng)求對(duì)應(yīng)一個(gè)方法 , 一個(gè)業(yè)務(wù)對(duì)應(yīng)一個(gè)Servlet類文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-498857.html
- 處理部門相關(guān)業(yè)務(wù)的對(duì)應(yīng)一個(gè)DeptServlet ,處理用戶相關(guān)業(yè)務(wù)的對(duì)應(yīng)一個(gè)UserServlet
重寫HttpServlet類提供的重載的參數(shù)含httpXxx的service模板方法,本類提供以后會(huì)調(diào)本類的service模板方法(但是就享受不到HTTP協(xié)議專屬的提醒)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-498857.html
// 模糊匹配 ,只要請(qǐng)求路徑是以"/dept"開(kāi)始的,都走這個(gè)Servlet
@WebServlet("/dept/*")
// @WebServlet({"/dept/list", "/dept/save", "/dept/edit", "/dept/detail", "/dept/delete", "/dept/modify"})
public class DeptServlet extends HttpServlet {
// 重寫service模板方法(并沒(méi)有重寫doGet或者doPost)
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 獲取servlet path
String servletPath = request.getServletPath();
if("/dept/list".equals(servletPath)){
doList(request, response);
} else if("/dept/save".equals(servletPath)){
doSave(request, response);
} else if("/dept/edit".equals(servletPath)){
doEdit(request, response);
} else if("/dept/detail".equals(servletPath)){
doDetail(request, response);
} else if("/dept/delete".equals(servletPath)){
doDel(request, response);
} else if("/dept/modify".equals(servletPath)){
doModify(request, response);
}
}
private void doList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 查看部門列表的業(yè)務(wù)邏輯
}
private void doSave(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 保存部門的業(yè)務(wù)邏輯
}
private void doEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 查看部門可修改的業(yè)務(wù)邏輯
}
private void doDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 查看部門詳情的業(yè)務(wù)邏輯
}
private void doDel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 刪除部門的業(yè)務(wù)邏輯
}
private void doModify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 修改部門的業(yè)務(wù)邏輯
}
}
到了這里,關(guān)于使用Servlet完成單表的增刪改查功能以及使用模板方法設(shè)計(jì)模式解決類爆炸問(wèn)題(重寫service模板方法)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!