国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

使用Servlet完成單表的增刪改查功能以及使用模板方法設(shè)計(jì)模式解決類爆炸問(wèn)題(重寫service模板方法)

這篇具有很好參考價(jià)值的文章主要介紹了使用Servlet完成單表的增刪改查功能以及使用模板方法設(shè)計(jì)模式解決類爆炸問(wèn)題(重寫service模板方法)。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

使用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)查看部門列表功能

使用Servlet完成單表的增刪改查功能以及使用模板方法設(shè)計(jì)模式解決類爆炸問(wèn)題(重寫service模板方法)
設(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)查看部門詳情功能

使用Servlet完成單表的增刪改查功能以及使用模板方法設(shè)計(jì)模式解決類爆炸問(wèn)題(重寫service模板方法)
用戶點(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)刪除部門功能

使用Servlet完成單表的增刪改查功能以及使用模板方法設(shè)計(jì)模式解決類爆炸問(wèn)題(重寫service模板方法)
用戶點(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)新增部門功能

使用Servlet完成單表的增刪改查功能以及使用模板方法設(shè)計(jì)模式解決類爆炸問(wèn)題(重寫service模板方法)
“新增部門”的按鈕在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)查看部門詳情可修改功能

使用Servlet完成單表的增刪改查功能以及使用模板方法設(shè)計(jì)模式解決類爆炸問(wèn)題(重寫service模板方法)

用戶點(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)修改部門功能

使用Servlet完成單表的增刪改查功能以及使用模板方法設(shè)計(jì)模式解決類爆炸問(wèn)題(重寫service模板方法)
用戶點(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類

  • 處理部門相關(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)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 使用Django框架完成用戶的增刪改查操作

    使用Django框架完成用戶的增刪改查操作,需要按照以下步驟進(jìn)行: 創(chuàng)建Django項(xiàng)目: 在命令行中進(jìn)入項(xiàng)目目錄,執(zhí)行以下命令創(chuàng)建一個(gè)新的Django項(xiàng)目: 其中projectname是你的項(xiàng)目名稱。 創(chuàng)建應(yīng)用: 在項(xiàng)目目錄下執(zhí)行以下命令創(chuàng)建一個(gè)新的應(yīng)用: 其中appname是你的應(yīng)用名稱。 配置

    2024年01月18日
    瀏覽(26)
  • nodejs使用eggjs創(chuàng)建項(xiàng)目,接入influxdb完成單表增刪改查

    nodejs使用eggjs創(chuàng)建項(xiàng)目,接入influxdb完成單表增刪改查

    轉(zhuǎn)載請(qǐng)注明出處: Eggjs 是 Node.js 服務(wù)端應(yīng)用開(kāi)發(fā)框架,它提供了一套約定,使開(kāi)發(fā)者能夠快速搭建、開(kāi)發(fā)和部署應(yīng)用。以下是 Egg.js 的一些特性和作用: 框架內(nèi)置了基于約定的目錄結(jié)構(gòu)、約定的擴(kuò)展機(jī)制和一些常用的插件,可以幫助開(kāi)發(fā)者快速搭建應(yīng)用。 Egg.js 遵循 MVC 的分

    2024年02月07日
    瀏覽(23)
  • 創(chuàng)建一個(gè)圖書信息管理的順序表,數(shù)據(jù)有書本序號(hào)、書名、價(jià)格,以及對(duì)順序表的增刪改查的操作(c++)

    創(chuàng)建一個(gè)圖書信息管理的順序表,數(shù)據(jù)有書本序號(hào)、書名、價(jià)格,以及對(duì)順序表的增刪改查的操作(c++)

    提示:文章寫完后,目錄可以自動(dòng)生成,如何生成可參考右邊的幫助文檔 創(chuàng)建一個(gè)書本信息的順序表,數(shù)據(jù)有書本序號(hào)、書名、價(jià)格,以及對(duì)順序表的增刪改查的操作。 提示:這里對(duì)文章進(jìn)行總結(jié): 例如:以上就是今天要講的內(nèi)容,本文僅僅簡(jiǎn)單介紹了創(chuàng)建一個(gè)書本信息的

    2024年02月07日
    瀏覽(23)
  • Django學(xué)習(xí)記錄:使用ORM操作MySQL數(shù)據(jù)庫(kù)并完成數(shù)據(jù)的增刪改查

    Django學(xué)習(xí)記錄:使用ORM操作MySQL數(shù)據(jù)庫(kù)并完成數(shù)據(jù)的增刪改查

    數(shù)據(jù)庫(kù)操作 MySQL數(shù)據(jù)庫(kù)+pymysql Django開(kāi)發(fā)操作數(shù)據(jù)庫(kù)更簡(jiǎn)單,內(nèi)部提供了ORM框架。 安裝第三方模塊 ORM可以做的事: 1、創(chuàng)建、修改、刪除數(shù)據(jù)庫(kù)中的表(不用寫SQL語(yǔ)句)。【無(wú)法創(chuàng)建數(shù)據(jù)庫(kù)】 2、操作表中的數(shù)據(jù)(不用寫SQL語(yǔ)句)。 1、自己創(chuàng)建數(shù)據(jù)庫(kù) 1)啟動(dòng)MySQL服務(wù) 2)自帶

    2024年02月14日
    瀏覽(97)
  • 表的增刪改查

    表的增刪改查

    1、創(chuàng)建表 mysql create table employee ( ? ? - id int(1) comment \\\'員工編號(hào)\\\', ? ? - name varchar(6) comment \\\'員工名字\\\', ? ? - gender varchar(2) comment \\\'員工性別\\\', ? ? - salary int (4) comment \\\'員工薪資\\\'); Query OK, 0 rows affected (0.01 sec) 2、插入數(shù)據(jù) insert employee values(1,\\\'張三\\\',\\\'男\(zhòng)\\',2000); insert into employee values

    2024年02月13日
    瀏覽(21)
  • 基于Servlet+JSP的增刪改查練手項(xiàng)目

    基于Servlet+JSP的增刪改查練手項(xiàng)目

    我們每寫一步,就測(cè)試一步,不要等到所有都寫好了再測(cè)試,如果都寫好了再測(cè)試,最后出錯(cuò)的話,會(huì)很崩潰,代碼量大,調(diào)試就不容易,話不多說(shuō),開(kāi)始今天的練手項(xiàng)目。下面的代碼,每一步都是按照我自己的步驟,一步一步敲出來(lái),調(diào)試出來(lái)的,大家第一遍可以跟著敲代

    2024年02月09日
    瀏覽(24)
  • 【MySQL】表的增刪改查

    【MySQL】表的增刪改查

    表的增刪查改簡(jiǎn)稱CRUD:Create(新增),Retrieve(查找),Update(修改),Delete(刪除)。 CRUD的操作對(duì)象是對(duì)表當(dāng)中的數(shù)據(jù),是典型的DML語(yǔ)句(Data Manipulation Language 數(shù)據(jù)操作語(yǔ)言)。 語(yǔ)法: 說(shuō)明: SQL中大寫的表示,[ ]中代表的是可選項(xiàng)。 SQL中的每個(gè) value_list 都表示插

    2024年02月02日
    瀏覽(28)
  • 表的增刪改查 進(jìn)階(二)

    表的增刪改查 進(jìn)階(二)

    ???個(gè)人主頁(yè):Dikz12 ??個(gè)人專欄:MySql ??格言:那些在暗處執(zhí)拗生長(zhǎng)的花,終有一日會(huì)馥郁傳香 歡迎大家??點(diǎn)贊?評(píng)論?收藏 目錄 3.新增 ?4.查詢 聚合查詢? 聚合函數(shù)? GROUP BY子句 ?HAVING ?聯(lián)合查詢? 內(nèi)連接(重點(diǎn)) 外連接(重點(diǎn)) ?左外連接 右外連接? 自連接 子連接? 合并

    2024年01月20日
    瀏覽(20)
  • MySQL表的增刪改查(基礎(chǔ))

    MySQL表的增刪改查(基礎(chǔ))

    目錄 1. CRUD 2. 新增(Create)? 2.1 單行數(shù)據(jù) + 全列插入? 2.2 多行數(shù)據(jù) + 指定列插入 ? 3. 查詢(Retrieve)? 3.1 全列查詢? 3.2 指定列查詢? 3.3 查詢字段為表達(dá)式 ? 3.4 別名 3.5 去重:DISTINCT ? 3.6 排序:ORDER BY? 3.7 條件查詢:WHERE? 3.8 分頁(yè)查詢:LIMIT ? 4. 修改(Update) ?5. 刪除(

    2024年01月17日
    瀏覽(21)
  • 【MYSQL】表的增刪改查(基礎(chǔ))

    【MYSQL】表的增刪改查(基礎(chǔ))

    語(yǔ)法: INSERT [INTO] table_name [(column [, column] ...)] VALUES(value_list) [, (value_list)] ... 案例: 語(yǔ)法: SELECT [DISTINCT] {* | {column [, column] ...} [FROM table_name] [WHERE ...] [ORDER BY column [ASC | DESC], ...] LIMIT ... 案例: 為查詢結(jié)果中的列指定別名,表示返回的結(jié)果集中,以別名作為該列的名稱 語(yǔ)法:

    2024年02月02日
    瀏覽(27)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包