1. 程式人生 > 其它 >Servlet單表CRUD

Servlet單表CRUD

Servlet單表CRUD

  • 使用Servlet完成對單表的CRUD(B/S結構)

  • 實現步驟

    • 第一步:準備一張資料庫表

      • CREATE TABLE `dept` (
        	deptno int primary key,
            dname varchar(255),
            loc varchar(255)
        );
        insert into dept(deptno,dname,loc) values(10,"銷售部","天津"),
        (20,"研發部","北京"),
        (30,"美術部","南京"),
        (40,"管理隊","上海");
        
    • 第二步:準備一套HTML頁面(專案原型)

      • 將HTML頁面中的連結跑通

      • 設定哪些頁面?(這些頁面並不是最原始的,是後面寫類的時候修改過的)

        • 歡迎頁面 index.html

          • <!DOCTYPE html>
            <html>
            	<head>
            		<meta charset="utf-8">
            		<title>歡迎使用OA系統</title>
            	</head>
            	<body>
            		<a href="/oa/dpet/list">檢視部門列表</a>
            	</body>
            </html>
            
            
        • 列表頁面 list.html (主頁面,內建刪除,增添,修改,查詢)(因為僅使用servlet所以html頁面要放在servlet中以字串的方式傳給瀏覽器)

          • <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>部門列表頁面</title>
            </head>
            <body>
                    <script type="text/javascript">
                        function del(deptno){
                            if(window.confirm("刪除不可恢復!")){
                                document.location.href = '"+contextPath+"/dept/delete?deptno=' + deptno;
                            }
                        }
                    </script>
                <h1 align="center">部門列表</h1><hr>
                <table border="1pax" align="center" width="50%">
                    <tr>
                        <th>序號</th>
                        <th>部門編號</th>
                        <th>部門名稱</th>
                        <th>操作</th>
                    </tr>
            <!--以上部分是靜態的-->
            <!--        以下這部分要根據資料庫表中的資料動態的變化-->
            -------------------------------------------------------------------------------------------
                    <tr>
                        <th>"+(++i)+"</th>
                        <th>"+deptno+"</th>
                        <th>"+dname+"</th>
                        <th>
                        <a href='javascript:void(0)' onclick='del("+deptno+")'>刪除</a>
                        <a href='"+contextPath+"/dept/edit?deptno="+deptno+"'>修改</a>
                        <a href='"+contextPath+"/dept/detail?deptno="+deptno+"'>詳情</a>
                        </th>
                    </tr>
                </table>>
            ----------------------------------------------------------------------------------------
            <hr>
                    <a href='"+contextPath+"/add.html'>新增部門</a>
            </body>
            </html>
            
        • 新增頁面 add.html

          • <!DOCTYPE html>
            <html>
            	<head>
            		<meta charset="utf-8">
            		<title>新增部門</title>
            	</head>
            	<body>
            		<h1>新增部門</h1>
            		<hr >
            		<form action="/oa/dept/add" method="post">
            			部門編號<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>
            
            
        • 修改頁面 edit.html

          • <!DOCTYPE html>
            <html>
            	<head>
            		<meta charset="utf-8">
            		<title>修改部門</title>
            	</head>
            	<body>
            		<h1>修改部門</h1>
            		<hr >
            		<form action="/oa/dept/del" method="post">
            			部門編號<input type="text" name="deptno" value=""+deptno+""/><br>
            			部門名稱<input type="text" name="dname" value=""+dname+""/><br>
            			部門位置<input type="text" name="loc" value=""+loc+""/><br>
            			<input type="submit" value="儲存"/><br>
            		</form>
            	</body>
            </html>
            
            
        • 查詢頁面 detail.html

          • <!DOCTYPE html>
            <html>
            <head>
            	<meta charset='utf-8'>
            	<title>部門詳情頁面</title>
            </head>
            <body>
            	<h1>部門詳情</h1><hr>
            	<br>               
            	部門編號: "+deptno+" <br>
            	部門名稱: "+dname+" <br>
            	部門位置: "+loc+" <br>       
            <input type='button' value='後退' onclick='window.history.back()' />");
            </body>
            </html>
            
    • 第三步:分析這個系統包含哪些功能?(一個功能對應一個servlet)

      • 什麼叫一個功能?
        • 只要這個操作連線了資料庫,就表示一個獨立的功能。
      • 包括那些功能?
        • 1.檢視部門列表
        • 2.新增部門
        • 3.查詢部門詳情
        • 4.刪除部門
        • 5.修改部門
    • 第四步:在IDEA中搭建開發環境

      • 建立webapp(給這個webapp新增servlet-api.jar和jsp-api.jar)
      • 向Webapp中新增連線資料庫驅動jar包(JDBC)
        • 在WEB-INF目錄下新建lib目錄,將jar包引進
      • JDBC工具類
      • 將準備好的html頁面拷貝到idea中
    • 實現功能

      • 1.檢視部門列表

        • 第一步:修改前端頁面的超連結,使用者先點選的就是這個超連結

          • <a href="/oa/dpet/list">檢視部門列表</a>
            
        • 第二步:編寫web.xml配置檔案

          • <servlet>
                    <servlet-name>list</servlet-name>
                    <servlet-class>com.servlet.DeptListServlet</servlet-class>
                </servlet>
                <servlet-mapping>
                    <servlet-name>list</servlet-name>
                    <url-pattern>/dept/list</url-pattern>
                </servlet-mapping>
            
        • 第三步:編寫DeptListServlet繼承HttpServlet

          • public class DeptListServlet extends HttpServlet {
                @Override
                protected void get(HttpServletRequest request, HttpServletResponse response)
                        throws ServletException, IOException {
                }
            
        • 第四步:在doGet方法中連線資料庫,動態獲取部門列表資訊

          • 將list.html中所有的雙引號換成單引號,因為out.print(""),這裡有一個雙引號容易衝突,使用Response將out輸出的html字串響應在瀏覽器上

          • 		Connection coon = null;
                    PreparedStatement ps = null;
                    ResultSet rs = null;
                    try {
                        //獲取資料庫連結
                      coon = DBUtil.getConnection();
                       //獲取預編譯資料庫操作物件
                       String sql = "select deptno,dname,loc from dept";
                       ps = coon.prepareStatement(sql);
                       //處理查詢結果集
                       rs = ps.executeQuery();
                       //遍歷輸出
                        int i = 0;
                        while (rs.next()){
                            String deptno = rs.getString("deptno");
                            String dname = rs.getString("dname");
                            String loc = rs.getString("loc");
            				//這部分是動態的
                            out.print("			<tr>");
                            out.print("				<th>"+(++i)+"</th>");
                            out.print("				<th>"+deptno+"</th>");
                            out.print("				<th>"+dname+"</th>");
                            out.print("				<th>");
                            out.print("				<a href='javascript:void(0)' onclick='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("				</th>");
                            out.print("			</tr>");
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }finally {
                        //釋放資源
                        DBUtil.close(coon,ps,rs);
                    }
            
      • 第二步:檢視部門詳情功能

        • 找到這個詳情是在list裡面所以要將其變為一個servlet資源路徑(這裡可以在urI裡面拼接deptno的值),這裡很巧妙把要不知道在Deatil中獲取的deptno封裝在了request請求中使得後續可以十分方便的動態查詢到需要的部門詳情資訊

          <a href='/oa/dept/detail?deptno="+deptno+"'>詳情</a>
          
        • 建立servlet,配置web.xml,開始編寫程式

          •     <servlet>
                    <servlet-name>detail</servlet-name>
                    <servlet-class>com.servlet.DeptDetialServlet</servlet-class>
                </servlet>
                <servlet-mapping>
                    <servlet-name>detail</servlet-name>
                    <url-pattern>/dept/detail</url-pattern>
                </servlet-mapping>
            
        • 開始編寫ServletDetail類的實現

          • 根據超連結拼接的deptno查詢資料庫中對應的dname,loc

            public class DeptDetialServlet extends HttpServlet {
                @Override
                protected void doGet(HttpServletRequest request, HttpServletResponse response)
                        throws ServletException, IOException {
                    response.setContentType("text/html;charset=utf-8");
                    PrintWriter out = response.getWriter();
                    //列印這個html頁面
                    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>");
                    out.print("<br>");
            
            
                    //連線資料庫查詢
                    Connection coon = null;
                    PreparedStatement ps = null;
                    ResultSet rs = null;
                    try {
                        String deptno = request.getParameter("deptno");
                        //獲取資料庫連結
                        coon = DBUtil.getConnection();
                        //獲取預編譯資料庫操作物件
                        String sql = "select deptno,dname,loc from dept where deptno = ?";
                        ps = coon.prepareStatement(sql);
                        ps.setString(1,deptno);
                        //處理查詢結果集
                        rs = ps.executeQuery();
                        if(rs.next()){
                            String dname = rs.getString("dname");
                            String loc = rs.getString("loc");
                            out.print("部門編號: "+deptno+" <br>");
                            out.print("部門名稱: "+dname+" <br>");
                            out.print("部門位置: "+loc+" <br>");
                        }
            
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }finally {
                        //釋放資源
                        DBUtil.close(coon,ps,rs);
                    }
            
                    out.print("<input type='button' value='後退' onclick='window.history.back()' />");
                    out.print("	</body>");
                    out.print("</html>");
            
                }
            }
            
            
      • 第三步:編寫部門刪除功能

      • 1.超連結跳轉到刪除的servlet

        • 配置xml檔案

          •     <servlet>
                    <servlet-name>delete</servlet-name>
                    <servlet-class>com.servlet.DeptDelServlet</servlet-class>
                </servlet>
                <servlet-mapping>
                    <servlet-name>delete</servlet-name>
                    <url-pattern>/dept/delete</url-pattern>
                </servlet-mapping>
            
        • //在list頁面點選刪除的超連結設定一個彈窗提示
          <a href='javascript:void(0)' onclick='del("+deptno+")'>刪除</a>
          //Script指令碼
          <script type='text/javascript'>
           	function del(deptno){
          		if(window.confirm('刪除不可恢復!'){
                      //這裡跳轉到刪除的servlet頁面,並將要刪除的deptno傳進去
          		document.location.href = '"+contextPath+"/dept/delete?deptno=' + deptno
          		}
          }
          </script>
          
          //在DelServlet中獲取部門編號
          String deptno = request.getParameter("deptno");
          //連線資料庫進行刪除
          coon = DBUtil.getConnection();
          coon.setAutoCommit(false);
          //獲取預編譯的操作物件
          String sql = "delete from dept where deptno = ?";
          ps = coon.prepareStatement(sql);
          ps.setString(1,deptno);
          //執行sql
          count = ps.executeUpdate();
          coon.commit();
          
          //刪除成功跳轉到該頁面
          if(count == 1){
              request.getRequestDispatcher("/dpet/list").forward(request,response);
          }
          
      • 第四步:編寫部門增添功能

        • 配置xml檔案

              <servlet>
                  <servlet-name>add</servlet-name>
                  <servlet-class>com.servlet.DeptAddServlet</servlet-class>
              </servlet>
              <servlet-mapping>
                  <servlet-name>add</servlet-name>
                  <url-pattern>/dept/add</url-pattern>
              </servlet-mapping>
          
        • //在list頁面編寫超連結跳轉到add.html
          String contextPath = request.getContextPath();
          <a href='"+contextPath+"/add.html'>新增部門</a>
          //add.html提交post表單到AddServlet
          <!DOCTYPE html>
          <html>
          	<head>
          		<meta charset="utf-8">
          		<title>新增部門</title>
          	</head>
          	<body>
          		<h1>新增部門</h1>
          		<hr >
          		<form action="/oa/dept/add" method="post">
          			部門編號<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>
              
          //AddServlet連線資料庫,插入欄位
                  request.setCharacterEncoding("utf-8");
                  String deptno = request.getParameter("deptno");
                  String dname = request.getParameter("dname");
                  String loc = request.getParameter("loc");
                  int count = 0;
                  Connection coon = null;
                  PreparedStatement ps = null;
          
          		 coon = DBUtil.getConnection();
                   //獲取資料庫操作物件
                   String sql = "insert into dept(deptno,dname,loc) values (?,?,?)";
                   ps = coon.prepareStatement(sql);
                   ps.setString(1,deptno);
                   ps.setString(2,dname);
                   ps.setString(3,loc);
                   //執行sql
                   count = ps.executeUpdate();
          //插入成功,跳轉到list頁面
          if(count ==1 ){
              request.getRequestDispatcher("/dpet/list").forward(request,response);
          }else{
              request.getRequestDispatcher("error.html").forward(request,response);
          }
          
        • 第五步:編寫部門修改功能

          • 點選list修改按鈕之後,跳轉到修改頁面,頁面上應該有原先的deptno,dname,loc等內容,這跟detail的功能是一樣的,然後在這個,將這部分內容放在post表單中點選提交,跳轉到doPost在doPost中連線資料庫進行修改操作

            • 編寫xml檔案

            •     <servlet>
                      <servlet-name>edit</servlet-name>
                      <servlet-class>com.servlet.DeptEditServlet</servlet-class>
                  </servlet>
                  <servlet-mapping>
                      <servlet-name>edit</servlet-name>
                      <url-pattern>/dept/edit</url-pattern>
              
            • //兩個超連結要配置好
              //這個超連結跳轉到EditServlet中的doGet裡獲取到deptno,查詢出來的結果放在post表單中
              <a href='"+contextPath+"/dept/edit?deptno="+deptno+"'>修改</a>
              //這個超連結跳轉到EditServlet中的doPost
              <form action="/oa/dept/edit" method="post">
              	部門編號<input type="text" name="deptno" value=""+deptno+""/><br>
              	部門名稱<input type="text" name="dname" value=""+dname+""/><br>
              	部門位置<input type="text" name="loc" value=""+loc+""/><br>
              	<input type="submit" value="儲存"/><br>
              </form>
              
          • 編寫DeptEditServlet類

            • //doGet類 使用者點選修改按鈕後根據deptno查詢出的資料放在post表單中
              protected void doGet(HttpServletRequest request, HttpServletResponse response)
                          throws ServletException, IOException {
                      String contextPath = request.getContextPath();
                      response.setContentType("text/html;charset=utf-8");
                      PrintWriter out = response.getWriter();
              
                      out.printf("<!DOCTYPE html>");
                      out.printf("<html>");
                      out.printf("<head>");
              		out.printf("<meta charset='utf-8'>");
              		out.printf("<title>修改部門</title>");
              	    out.printf("</head>");
              	    out.printf("<body>");
              		out.printf("<h1>修改部門</h1>");
              		out.printf("<hr >");
              
                      //獲取主鍵資訊
                      String deptno = request.getParameter("deptno");
                      Connection coon = null;
                      PreparedStatement ps = null;
                      ResultSet rs = null;
                      try {
                          //連線資料庫動態獲取要修改的資訊
                          coon = DBUtil.getConnection();
                          String sql = "select deptno,dname,loc from dept where deptno= ?";
                          ps = coon.prepareStatement(sql);
                          ps.setString(1,deptno);
                          rs = ps.executeQuery();
                          if (rs.next()){
                              String dname = rs.getString("dname");
                              String loc = rs.getString("loc");
                              out.printf("<form action='"+contextPath+"/dept/edit' method='post'>");
                              out.printf("部門編號<input type='text' name='deptno' value='"+deptno+"' readonly/><br>");
                              out.printf("部門名稱<input type='text' name='dname' value='"+dname+"'/><br>");
                              out.printf("部門位置<input type='text' name='loc' value='"+loc+"'/><br>");
                              out.printf("<input type='submit' value='修改'/><br>");
                              out.printf("</form>");
                          }
              
              
                      } catch (SQLException e) {
                          e.printStackTrace();
                      }finally {
                          DBUtil.close(coon,ps,rs);
                      }
              //doPost 
                      protected void doPost(HttpServletRequest request, HttpServletResponse response)
                          throws ServletException, IOException {
                      //解決請求體中文亂碼
                      request.setCharacterEncoding("UTF-8");
                      String deptno = request.getParameter("deptno");
                      String dname = request.getParameter("dname");
                      String loc = request.getParameter("loc");
                      //連線資料庫
                      Connection coon = null;
                      PreparedStatement ps = null;
                      int count = 0;
              
                      try {
                          coon = DBUtil.getConnection();
                          String sql = "update dept set dname = ?,loc=? where deptno = ?";
                          ps = coon.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(coon,ps,null);
                      }
              
                      if(count == 1){
                          //轉發
                          request.getRequestDispatcher("/dpet/list").forward(request,response);
                      }else{
                          request.getRequestDispatcher("/error.html").forward(request,response);
                      }
                  }
              
          • 思路:前端----->後端,根據前端使用者點選的操作一步一步完成相應的功能,這裡使用者在List頁面點選修改按鈕跳轉到

            '"+contextPath+"/dept/edit?deptno="+deptno+"' EditServlet中的doGet方法,在doGet方法的post表單(這裡的doGet方法涉及到一個查詢操作將原來的資料展示在文字框內)中修改資料之後,點選提交再跳轉到EditServlet中的doPost方法,doPost根據post表單中的內容獲取到資料,連線資料庫進行更新操作