当前位置:Gxlcms > 数据库问题 > 简单使用JDBC和Servlet实现用户注册和登录功能

简单使用JDBC和Servlet实现用户注册和登录功能

时间:2021-07-01 10:21:17 帮助过:23人阅读

一、大体的编码思路

1.1、注册功能

  1. 获取注册页面提交的username、password和repeatPassword;

  2. 判断password和 repeatPassword是否一致,一致就继续执行程序,不一致则结束程序;

  3. 遍历数据库中tb_user,查看数据库中是否存在username,存在则结束程序,不存在则继续进行程序,实现注册功能;

1.2、登录功能

  1. 获取登录页面的username和password;
  2. 遍历数据库中tb_user,是否存在username,存在则继续执行程序,不存在,则结束程序;
  3. 遍历数据库中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&nbsp;&nbsp;<input type="radio" name="gender" value="male" class="radioMid" />
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        Female&nbsp;&nbsp;<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);                    

人气教程排行