JSP培訓(9)——使用MVC模式完成刪除和修改功能

來源:互聯網
上載者:User
 

目標:l         進一步理解MVC模式;l         掌握刪除功能的基本實現過程;l         掌握修改功能的基本實現過程。主要內容:l         使用MVC完成刪除功能;l         使用MVC模式完成資訊更新功能。1、 如何使用MVC模式完成刪除功能根據MVC模式的特點,分別考慮MVC的3個部分。n         首先考慮V部分:u       輸入:通常刪除功能是在查詢的基礎上完成的,所以在使用者資訊列表介面上可以添加刪除的超鏈。u       輸出:提示使用者刪除是否成功,可以採用單獨的介面,也可以在其他頁面中顯示。我們採用第二種方式,在使用者列表介面中顯示提示資訊。n         其次考慮M部分:需要在User.java中添加刪除使用者的方法即可。n         最後考慮C部分:擷取使用者要刪除的使用者名稱,然後調用M部分完成刪除,最後轉向使用者資訊列表介面。下面分別實現。2、 在userlist.jsp檔案中添加刪除超鏈和提示資訊1)添加刪除超鏈(紅色部份):           <c:forEach var="user" items="${users}">                     <tr>                            <td>                                   ${user.username}                            </td>                            <td>                                   ${user.userpass}                            </td>                            <td>                                   <a href="deleteUser?username=${user.username}">刪除</a>                            </td>                     </tr>              </c:forEach>    注意:刪除的時候需要知道要刪除的使用者的名字(這裡名字作為主鍵),所以通過參數傳遞名字。2)添加提示資訊:<font color="red"> ${deleteinfo} </font>3)修改後的代碼如下:<%@ page contentType="text/html;charset=gb2312"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><font color="red"> ${addinfo} </font><font color="red"> ${deleteinfo} </font><br><c:if test="${pageNo!=1}">       <a href="getAllUser?pageNo=1">第一頁</a>       <a href="getAllUser?pageNo=${pageNo-1}">上一頁</a></c:if><c:if test="${pageNo!=pageCounter}">       <a href="getAllUser?pageNo=${pageNo+1}">下一頁</a>       <a href="getAllUser?pageNo=${pageCounter}">最後一頁</a></c:if><br><table width="200" border="1" height="56">       <tbody>              <tr>                     <td>                            使用者名稱                     </td>                     <td>                            口令                     </td>                     <td>                                                 </td>              </tr>              <c:forEach var="user" items="${users}">                     <tr>                            <td>                                   ${user.username}                            </td>                            <td>                                   ${user.userpass}                            </td>                            <td>                                   <a href="deleteUser?username=${user.username}">刪除</a>                            </td>                     </tr>              </c:forEach>       </tbody></table>3、 編寫M部分:在User.java中添加方法在User.java中添加deleteUser方法,參考代碼如下:public boolean deleteUser(String username) {        Connection con = null;        Statement stmt = null;        boolean b; // 表示刪除成功與否         try {               // 指出串連資料庫所需要的驅動程式               Class.forName("oracle.jdbc.driver.OracleDriver");                // 建立與資料庫之間的串連               con = DriverManager.getConnection(                             "jdbc:oracle:thin:@myserver:1521:mydb", "scott",                             "tiger");                // 編寫查詢資料庫資訊的SQL語句               String sql = "delete from usertable where username='" + username + "'";                // 建立語句對象,用於執行SQL語句               stmt = con.createStatement();                // 執行沒有結果集返回的語句,返回的是影響資料庫表中記錄的個數               int n = stmt.executeUpdate(sql);                if (n > 0)                      b = true;               else                      b = false;        } catch (Exception e) {               b = false;        } finally {              // 關閉相關對象               if (stmt != null)                      try {                             stmt.close();                      } catch (Exception ee) {                      }               if (con != null)                      try {                             con.close();                      } catch (Exception ee) {                      }        }        return b;}注意:紅色部分需要修改成您自己的伺服器和資料庫。4、 編寫C部分:添加DeleteUser控制器DeleteUser.java的代碼如下:package servlet; import java.io.IOException;import java.io.PrintWriter; import javabean.User; import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class DeleteUser extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)               throws ServletException, IOException {        //擷取資訊        String username = request.getParameter("username");                // 調用JavaBean        User user = new User();        boolean b = user.deleteUser(username);                // 傳遞刪除成功或失敗的資訊        String info;        if(b)               info = "刪除成功!";        else                info = "刪除失敗!";    request.setAttribute("deleteinfo",info);                // 選擇介面對使用者響應        RequestDispatcher rd = request.getRequestDispatcher("getAllUser");        rd.forward(request,response); }public void doPost(HttpServletRequest request, HttpServletResponse response)               throws ServletException, IOException {         doGet(request,response);}}5、 如何使用MVC模式實現修改功能修改功能本身包括兩個過程:使用者選擇要修改的使用者,然後把該使用者的資訊顯示在修改介面上;使用者進行修改,修改之後提交,伺服器完成修改功能。對於第一個功能,採用MVC模式:l         V部分:n         輸入:在使用者列表介面上添加“修改”超鏈。n         輸出:使用者資訊修改介面,把查詢到的資訊顯示在修改介面上。l         M部分:編寫按照使用者名稱查詢使用者資訊的方法。l         C部分:擷取要刪除的使用者的名字,調用M部分的查詢方法,得到使用者資訊,傳遞到修改介面,使用修改介面對使用者響應。對於第二部分,採用MVC模式:l         V部分n         輸入:上面編寫的修改介面。n         輸出:使用者資訊列表介面l         M部分:編寫使用者資訊修改的方法。l         C部分:擷取使用者輸入的資訊,調用M部分完成修改,轉向列表介面對使用者進行響應。下面分別介紹實現方法。6、 修改使用者資訊列表介面修改後的代碼如下:<%@ page contentType="text/html;charset=gb2312"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><font color="red"> ${addinfo} </font><font color="red"> ${deleteinfo} </font><font color="red"> ${updateinfo} </font><br><c:if test="${pageNo!=1}"><a href="getAllUser?pageNo=1">第一頁</a><a href="getAllUser?pageNo=${pageNo-1}">上一頁</a></c:if><c:if test="${pageNo!=pageCounter}"><a href="getAllUser?pageNo=${pageNo+1}">下一頁</a><a href="getAllUser?pageNo=${pageCounter}">最後一頁</a></c:if><br><table width="200" border="1" height="56"><tbody>        <tr>               <td>                      使用者名稱               </td>               <td>                      口令               </td>               <td>                                     </td>        </tr>        <c:forEach var="user" items="${users}">               <tr>                      <td>                             ${user.username}                      </td>                      <td>                             ${user.userpass}                      </td>                      <td>                             <a href="findUser?username=${user.username}">修改</a>                      </td>                      <td>                             <a href="deleteUser?username=${user.username}">刪除</a>                      </td>               </tr>        </c:forEach></tbody></table>7、 編寫資訊修改介面參考代碼如下:<%@ page contentType="text/html;charset=gb2312"%> 修改使用者<br><form name="form1" method="post" action="updateUser">    使用者名稱:${user.username}<input type="hidden" name="username" value="${user.username}"><br>   口令:<input type="text" name="userpass" value="${user.userpass}"><br>       <input type="submit" value="修改"><input type="reset" value="重設"></form>8、 在User.java中添加查詢資訊的方法    public User findUserByName(String username) {              Connection con = null;              Statement stmt = null;              ResultSet rs = null;                            try {                     // 指出串連資料庫所需要的驅動程式                     Class.forName("oracle.jdbc.driver.OracleDriver");                      // 建立與資料庫之間的串連                     con = DriverManager.getConnection(                                   "jdbc:oracle:thin:@myserver:1521:mydb", "scott",                                   "tiger");                      // 編寫查詢資料庫資訊的SQL語句                     String sql = "select * from usertable where username='" + username + "'";                      // 建立語句對象,用於執行SQL語句                     stmt = con.createStatement();                      // 執行沒有結果集返回的語句,返回的是影響資料庫表中記錄的個數                     rs = stmt.executeQuery(sql);                                          if(rs.next()){                            User user = new User();                            String userpass = rs.getString(2);                            user.setUsername(username);                            user.setUserpass(userpass);                            return user;                     }                                 } catch (Exception e) {                     return null;              } finally {                     // 關閉相關對象                     try{                            rs.close();                     }catch(Exception e){}                     if (stmt != null)                            try {                                   stmt.close();                            } catch (Exception ee) {                            }                     if (con != null)                            try {                                   con.close();                            } catch (Exception ee) {                            }              }              return null;       }注意:紅色部分需要修改成您自己的伺服器和資料庫。9、 在User.java中添加“修改資訊”的方法public boolean update() {        Connection con = null;        Statement stmt = null;        boolean b;                try {               // 指出串連資料庫所需要的驅動程式               Class.forName("oracle.jdbc.driver.OracleDriver");                // 建立與資料庫之間的串連               con = DriverManager.getConnection(                             "jdbc:oracle:thin:@myserver:1521:mydb", "scott",                             "tiger");                // 編寫更新的sQL語句               String sql = "update usertable set userpass = '"+userpass+"' where username='" + username + "'";                // 建立語句對象,用於執行SQL語句               stmt = con.createStatement();                // 執行沒有結果集返回的語句,返回的是影響資料庫表中記錄的個數               int n = stmt.executeUpdate(sql);                              if(n>0)                      b=true;               else                      b=false;        } catch (Exception e) {               b = false;        } finally {               if (stmt != null)                      try {                             stmt.close();                      } catch (Exception ee) {                      }               if (con != null)                      try {                             con.close();                      } catch (Exception ee) {                      }        }        return b;}注意:紅色部分需要修改成您自己的伺服器和資料庫。10、              編寫查詢資訊的Servlet參考代碼如下:package servlet; import java.io.IOException;import java.io.PrintWriter; import javabean.User; import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class FindUser extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)               throws ServletException, IOException {        doPost(request,response);}public void doPost(HttpServletRequest request, HttpServletResponse response)               throws ServletException, IOException {       // 擷取資訊        String username = request.getParameter("username");                //調用Javabean        User user = new User();        user = user.findUserByName(username);                // 傳遞值        request.setAttribute("user", user);         // 選擇介面對使用者進行響應        RequestDispatcher rd = request.getRequestDispatcher("updateuser.jsp");        rd.forward(request, response);                          }}11、              編寫修改資訊的Servlet參考代碼如下:package servlet; import java.io.IOException;import java.io.PrintWriter; import javabean.User; import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class UpdateUser extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)               throws ServletException, IOException {        doPost(request,response);}public void doPost(HttpServletRequest request, HttpServletResponse response)               throws ServletException, IOException {   // 擷取資訊        String username = request.getParameter("username");        String userpass = request.getParameter("userpass");                //調用Javabean        User user = new User();        user.setUsername(username);        user.setUserpass(userpass);        boolean b = user.update();                // 傳遞值        String info ;        if(b)               info="修改成功!";        else               info="修改失敗!";         // 選擇介面對使用者進行響應        RequestDispatcher rd = request.getRequestDispatcher("getAllUser");        rd.forward(request, response);      }}

 

參考教材:《Java Web程式設計基礎教程》

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.