簡單的瀏覽了一下Servlet和JDBC方面的知識,於是寫了一下簡單使用JDBC和Servlet實現用戶注冊和登錄功能,具體實現如下:
一、大體的編碼思路
1.1、注冊功能
-
獲取注冊頁面提交的username、password和repeatPassword;
-
判斷password和 repeatPassword是否一致,一致就繼續執行程序,不一致則結束程序;
-
遍歷數據庫中tb_user,查看數據庫中是否存在username,存在則結束程序,不存在則繼續進行程序,實現注冊功能;
1.2、登錄功能
- 獲取登錄頁面的username和password;
- 遍歷數據庫中tb_user,是否存在username,存在則繼續執行程序,不存在,則結束程序;
- 遍歷數據庫中tb_user,查找對應username的password,判斷password是否與登錄頁面的password一致,一致則完成登錄,不一致則跳出。
二、代碼實現
2.1、數據庫表設計(tb_user)
create table tb_user ( id int not null primary key auto_increment, -- id主鍵,設置不為空且自動增長 username varchar(40) not null, -- 賬戶名稱,設置不為空 password varchar(40) not null, -- 密碼,設置不為空 name varchar(40) default null, -- 用戶真實姓名,默認為空 gender varchar(20) default null, -- 用戶性別,默認為空 phonenumber varchar(30) default null, -- 用戶手機號碼,默認為空 identitycode varchar(30) default null -- 用戶身份證號碼,默認為空 );
2.2、頁面設計
2.2.1、 主頁面設計
代碼設計:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="./css/index.css" /> <title>Welcome to my website</title> </head> <body> <ul> <a href="pages/login.jsp"><li>Log In</li></a> <a href="pages/regist.jsp" class="right40"><li>Regist</li></a> </ul> </body> </html>
樣式表:
* { margin: 0; padding: 0; } ul { display: block; height: 80px; width: 520px; margin: auto; margin-top: 150px; } ul li { list-style: none; float: left; display: block; height: 80px; width:240px; text-align: center; } ul a { display: block; background-color: #98ECAC; float: left; line-height: 80px; font-size: 26px; font-weight: bold; color: white; font-family: "Monaco"; } ul a:hover { color: #7C81E2; } .right40 { margin-left: 40px; }
2.2.2、 登錄和注冊頁面
注冊頁面代碼設計:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="../css/style.css" /> <title>Regist Pages</title> </head> <body> <form action="../RegistServlet" method="post"> <table> <tr> <td class="alignRight"> Username: </td> <td> <input type="text" name="username" /> </td> </tr> <tr> <td class="alignRight"> Password: </td> <td> <input type="password" name="password" /> </td> </tr> <tr> <td class="alignRight"> Confirm-Password: </td> <td> <input type="password" name="repeatPsd" /> </td> </tr> <tr> <td class="alignRight"> Name: </td> <td> <input type="text" name="truename" /> </td> </tr> <tr> <td class="alignRight"> Gender: </td> <td> Male <input type="radio" name="gender" value="male" class="radioMid" /> Female <input type="radio" name="gender" value="Female" class="radioMid" /> </td> </tr> <tr> <td class="alignRight"> Phone-Number: </td> <td> <input type="text" name="phone" /> </td> </tr> <tr> <td class="alignRight"> Identity-Code: </td> <td> <input type="text" name="indetity"> </td> </tr> </table> <input type="submit" value="Regist" class="submit" /> </form> </body> </html>
登錄頁面代碼設計:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="../css/style.css" /> <title>Log In Page</title> </head> <body> <form action="../LoginServlet" method="post"> <table> <tr> <td class="alignRight"> Username: </td> <td> <input type="text" name="username" /> </td> </tr> <tr> <td class="alignRight"> Password: </td> <td> <input type="password" name="password" /> </td> </tr> </table> <input type="submit" value="Log In" class="submit" /> </form> </body> </html>
登錄和注冊頁面樣式表:
* { margin: 0; padding: 0; } form { display: block; height: auto; width: 450px; margin: 100px auto; } form table tr { height: 40px; } form table tr td { height: 40px; width: 280px; line-height: 40px; } form table tr td input { height: 32px; border: 1px solid #BABABA; border-radius: 6px; } .alignRight { text-align: right; line-height: 40px; font-size: 16px; font-family: "Monaco"; width: 200px; } .radioMid { vertical-align:middle; } .submit { display: block; height: 40px; width: 250px; color: white; font-weight: bold; font-size: 18px; background-color: #98ECAC; border-radius: 8px; margin: 15px auto; }
2.3、工具類和Servlet類設計和配置
2.3.1、工具類設計——獲取Connection對象
在JDBC的操作中,要頻繁的獲取Connection對象,所以此時,在項目下創建com.utils工具包,在包中編寫一個獲取Connection對象的工具類。
1 package com.utils; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.SQLException; 6 7 public class GetConnection { 8 9 Connection conn = null; 10 11 public Connection getConnection() throws ClassNotFoundException { 12 String driver="com.mysql.jdbc.Driver"; //驅動路徑 13 String url="jdbc:mysql://localhost:3306/martin"; //數據庫地址 14 String user="root"; //訪問數據庫的用戶名 15 String password="123456"; //用戶密碼 16 17 Class.forName(driver); 18 try { 19 conn = DriverManager.getConnection(url,user,"admin"); 20 } catch (SQLException e) { 21 // TODO Auto-generated catch block 22 e.printStackTrace(); 23 } 24 //返回Connection對象 25 return conn; 26 } 27 }
2.3.2、Servlet類設計
實現注冊功能的RegistServlet
1 package com.martin; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.sql.Connection; 6 import java.sql.PreparedStatement; 7 import java.sql.ResultSet; 8 import java.sql.SQLException; 9 import java.sql.Statement; 10 import java.util.ArrayList; 11 import java.util.List; 12 13 import javax.servlet.ServletException; 14 import javax.servlet.annotation.WebServlet; 15 import javax.servlet.http.HttpServlet; 16 import javax.servlet.http.HttpServletRequest; 17 import javax.servlet.http.HttpServletResponse; 18 19 import com.utils.GetConnection; 20 21 @WebServlet("/RegistServlet") 22 public class RegistServlet extends HttpServlet { 23 24 protected void doPost(HttpServletRequest request, HttpServletResponse response) 25 throws ServletException, IOException { 26 27 //設置請求編碼、響應方式和編碼方式 28 request.setCharacterEncoding("UTF-8"); 29 response.setCharacterEncoding("UTF-8"); 30 response.setContentType("text/html"); 31 32 PrintWriter out = response.getWriter(); 33 34 Statement st = null; 35 ResultSet rs = null; 36 37 PreparedStatement ptst = null; 38 //創建用戶名集合 39 List<String> usernameList = new ArrayList<String>(); 40 41 //獲取注冊用戶名 42 String registName = request.getParameter("username"); 43 //獲取注冊用戶密碼 44 String registPassword = request.getParameter("password"); 45 //獲取注冊用戶二次密碼 46 String registRepeatpsd = request.getParameter("repeatPsd"); 47 //獲取注冊用戶真實姓名 48 String userTrueName = request.getParameter("truename"); 49 //獲取用戶性別 50 String gender = request.getParameter("gender"); 51 //獲取注冊用戶手機號碼 52 String phoneNumber = request.getParameter("phone"); 53 //獲取用戶身份證號碼 54 String identityCode = request.getParameter("indetity"); 55 56 //獲取與MySQL鏈接的Connection對象 57 Connection conn = null; 58 try { 59 conn = new GetConnection().getConnection(); 60 /** 61 * 判斷兩次密碼是否一致: 62 * 是:繼續注冊; 63 * 否:返回錯誤; 64 */ 65 if (registPassword.equals(registRepeatpsd)) { 66 try { 67 /** 68 * 判斷用戶表中是否已經存在該用戶 69 * 1.遍歷tb_user表中所用的username字段 70 * 2.將username字段中的所有數據存入集合中; 71 * 3.判斷集合中和否含有注冊的用戶名 72 * 3.1:如果有,返回到error頁面 73 * 3.2:如果沒有,進行注冊操作 74 */ 75 76 //遍歷tb_user表中username字段 77 String select = "select username from tb_user"; 78 st = conn.createStatement(); 79 rs = st.executeQuery(select); 80 //將username字段的所有數據存入集合中 81 82 while (rs.next()) { 83 usernameList.add(rs.getString(1)); 84 } 85 //關閉ResultSet和Statement鏈接 86 rs.close(); 87 st.close(); 88 89 } catch (SQLException e) { 90 // TODO Auto-generated catch block 91 e.printStackTrace(); 92 } 93 94 if (usernameList.contains(registName)) { 95 out.println("用戶名已注冊,請重新嘗試。"); 96 } else { 97 String insert = "insert into tb_user(username,password,name,gender,phonenumber,identitycode) values(?,?,?,?,?,?)"; 98 try { 99 ptst = conn.prepareStatement(insert); 100 //設置ptst參數 101 ptst.setString(1, registName); 102 ptst.setString(2,registPassword); 103 ptst.setString(3, userTrueName); 104 ptst.setString(4, gender); 105 ptst.setString(5,phoneNumber); 106 ptst.setString(6, identityCode); 107 //執行sql語句 108 ptst.execute(); 109 out.println("歡迎注冊。"); 110 //關閉關閉ResultSet和Statement鏈接 111 ptst.close(); 112 113 } catch (SQLException e) { 114 // TODO Auto-generated catch block 115 e.printStackTrace(); 116 } 117 118 } 119 } else { 120 out.println("兩次密碼輸入不一致,請重新嘗試。"); 121 } 122 } catch (ClassNotFoundException e1) { 123 // TODO Auto-generated catch block 124 e1.printStackTrace(); 125 } finally { 126 try { 127 //關閉Connection鏈接 128 if (conn != null) { 129 conn.close(); 130 } 131 } catch (SQLException e) { 132 // TODO Auto-generated catch block 133 e.printStackTrace(); 134 } 135 } 136 137 out.flush(); 138 out.close(); 139 140 } 141 142 }
實現登錄功能的LoginServlet
1 package com.martin; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.sql.Connection; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 import java.sql.Statement; 9 import java.util.ArrayList; 10 import java.util.List; 11 12 import javax.servlet.ServletException; 13 import javax.servlet.annotation.WebServlet; 14 import javax.servlet.http.HttpServlet; 15 import javax.servlet.http.HttpServletRequest; 16 import javax.servlet.http.HttpServletResponse; 17 18 import com.mysql.jdbc.PreparedStatement; 19 import com.utils.GetConnection; 20 21 @WebServlet("/LoginServlet") 22 public class LoginServlet extends HttpServlet { 23 24 protected void doPost(HttpServletRequest request, HttpServletResponse response) 25 throws ServletException, IOException { 26 //設置請求編碼、響應方式和編碼方式 27 request.setCharacterEncoding("UTF-8"); 28 response.setCharacterEncoding("UTF-8"); 29 response.setContentType("text/html"); 30 31 PrintWriter out = response.getWriter(); 32 33 Connection conn = null; 34 Statement st = null; 35 ResultSet rs = null; 36 PreparedStatement ptst = null; 37 //獲取登錄頁面提交的數據 38 String loginName = request.getParameter("username"); 39 String loginPassword = request.getParameter("password"); 40 //sql語句 41 String selectUsername = "select username from tb_user"; 42 String selectPassword = "select password from tb_user where username = ?"; 43 44 try { 45 //獲取與數據庫的鏈接 46 conn = new GetConnection().getConnection(); 47 //遍歷tb_user表,將數據庫中所有username存入集合中 48 st = conn.createStatement(); 49 rs = st.executeQuery(selectUsername); 50 List<String> usernameList = new ArrayList<String>(); 51 while (rs.next()) { 52 usernameList.add(rs.getString(1)); 53 } 54 //關閉連接 55 if (rs != null) { 56 rs.close(); 57 } 58 if (st != null) { 59 st.close(); 60 } 61 //判斷集合中是否存在所要登錄的username 62 if (usernameList.contains(loginName)) { 63 //查找username對應的password 64 List<String> passwordList = new ArrayList<String>(); 65 ptst = (PreparedStatement) conn.prepareStatement(selectPassword); 66 //設置ptst參數 67 ptst.setString(1, loginName); 68 rs = ptst.executeQuery(); 69 while (rs.next()) { 70 passwordList.add(rs.getString(1)); 71 } 72 //判斷數據庫與登錄頁面提交的password是否一致 73 if (passwordList.get(0).equals(loginPassword)) { 74 out.println("歡迎登錄。"); 75 } else { 76 out.println("密碼錯誤,請重新嘗試。"); 77 } 78 if (rs != null) { 79 rs.close(); 80 } 81 if (ptst != null) { 82 ptst.close(); 83 } 84 85 } else { 86 out.println("用戶名不存在,請稍后再撥..."); 87 } 88 89 } catch (ClassNotFoundException e) { 90 // TODO Auto-generated catch block 91 e.printStackTrace(); 92 } catch (SQLException e) { 93 // TODO Auto-generated catch block 94 e.printStackTrace(); 95 } finally { 96 //關閉鏈接 97 if (conn != null) { 98 try { 99 conn.close(); 100 } catch (SQLException e) { 101 // TODO Auto-generated catch block 102 e.printStackTrace(); 103 } 104 } 105 } 106 out.flush(); 107 out.close(); 108 } 109 110 }
2.3.3、Servlet類配置——web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://xmlns.jcp.org/xml/ns/javaee" 4 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 5 id="WebApp_ID" version="3.1"> 6 <display-name>LogAndRegist</display-name> 7 <welcome-file-list> 8 <welcome-file>index.html</welcome-file> 9 <welcome-file>index.htm</welcome-file> 10 <welcome-file>index.jsp</welcome-file> 11 <welcome-file>default.html</welcome-file> 12 <welcome-file>default.htm</welcome-file> 13 <welcome-file>default.jsp</welcome-file> 14 </welcome-file-list> 15 <servlet> 16 <servlet-name>RegistServlet</servlet-name> 17 <servlet-class>com.martin.RegistServlet</servlet-class> 18 </servlet> 19 <servlet-mapping> 20 <servlet-name>RegistServlet</servlet-name> 21 <url-pattern>/*/RegistServlet</url-pattern> 22 </servlet-mapping> 23 </web-app>