JavaWeb-连接数据库实现用户登录、注册、修改密码(全代码)

上一篇博客中我通过使用HttpServlet完成一个假登录,这篇博客我将通过JDBC连接数据库,使其实现简单的用户登录、注册以及更改密码

一、MySQL:

MySQL部分代码:

-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users`  (
  `uid` int NOT NULL AUTO_INCREMENT,
  `username` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `pwd` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `email` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `sex` varchar(4) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  PRIMARY KEY (`uid`) USING BTREE,
  UNIQUE INDEX `username`(`username` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1017 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES (1002, '张三', '15915963', '22782@qq.com', '男');
INSERT INTO `users` VALUES (1003, '李四', '123000', '69307@qq.com', '男');
INSERT INTO `users` VALUES (1004, '马冬梅', '123456', 'madongmei@163.com', '女');

二、Java

项目结构:

bean/User存放用户的实体类,实现了序列化接口,定义私有属性,set,get方法的普通java类
dao/impl/UserDao 接口,声明所需要的所有方法
dao/impl/UserDaoImpl 用在和数据直接交互,比如常用的是定义交互数据库的类或接口
servlet/Enroll 继承HttpServlet类,重写doGet方法和doPost方法,接收注册信息
servlet/Forget 更改密码
servlet/Login 登录
util/JDBCUtil 连接数据库
util/RegexUtil 判断邮箱格式

bean/

User代码:
package com.bing.bean;

public class User {
    private Integer uid;
    private String username;
    private String password;
    private String email;
    private String sex;

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}

dao/

EnrollDao代码:
package com.bing.dao;

import com.bing.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class EnrollDao {

    Connection con = null;// 连接源
    PreparedStatement ps = null;// 预处理sql语句
    ResultSet rs = null;// 结果集

    /*
     * 查询数据库是否有这个用户,有则true,没有则false
     * */
    public boolean userExists(String username) {
        boolean bo = false;
        con = JDBCUtil.getCon();
        if (con != null) {
            System.out.println("数据库连接成功~");
            String sql = "select * from users where username = ? ";
            try {
                ps = con.prepareStatement(sql);
                ps.setString(1, username);
                rs = ps.executeQuery();
                while (rs.next()) {
                    // 如果有数据,bo为true,结束循环
                    bo = true;
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                JDBCUtil.close(rs, ps, con);
            }
        } else {
            System.out.println("数据库连接失败!");
        }
        return bo;// 返回boolean值,判断是否有这个用户
    }
    /*
     * 向数据库添加账号信息
     * */
    public boolean register(String user, String pwd, String email, String sex) {
        boolean bo = false;
        if (!userExists(user)) {
            con = JDBCUtil.getCon();
            if (con != null) {
                System.out.println("数据库连接成功~");
                String sql = "insert into users(username,pwd,email,sex) values(?,?,?,?) ";
                try {
                    ps = con.prepareStatement(sql);
                    ps.setString(1, user);
                    ps.setString(2, pwd);
                    ps.setString(3, email);
                    ps.setString(4, sex);
                    int affectedRows = ps.executeUpdate();// 受影响的行数赋值给affectedRows
                    if (affectedRows > 0) {
                        bo = true;// 大于0则有行数受影响 数据库发生了改变 数据添加成功
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    JDBCUtil.close(ps, con);
                }

            } else {
                System.out.println("数据库连接失败!");
            }
        }
        return bo;// 返回boolean值 判断数据是否添加成功
    }

}
ForgetDao代码:
package com.bing.dao;

import com.bing.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ForgetDao {
    Connection con = null;// 连接源
    PreparedStatement ps = null;// 预处理sql语句
    ResultSet rs = null;// 结果集

    /*
    * 查询用户名是否与邮箱匹配
    * */
    public boolean userExists(String username, String email) {
        boolean bo = false;
        con = JDBCUtil.getCon();
        if (con != null) {
            System.out.println("数据库连接成功~");
            String sql = "select * from users where username = ? and email = ?";
            try {
                ps = con.prepareStatement(sql);
                ps.setString(1, username);
                ps.setString(2, email);
                rs = ps.executeQuery();
                while (rs.next()) {
                    bo = true;
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                JDBCUtil.close(rs, ps, con);
            }
        } else {
            System.out.println("数据库连接失败!");
        }
        return bo;
    }
    /*
    * 如果用户名和邮箱匹配,则可以操作更改密码
    * */
    public boolean change(String user, String pwd, String email) {
        boolean bo = false;
        if (userExists(user,email)) {
            con = JDBCUtil.getCon();
            if (con != null) {
                System.out.println("数据库连接成功~");
                String sql = "update users set pwd = ? where username = ?";
                try {
                    ps = con.prepareStatement(sql);
                    ps.setString(1, pwd);
                    ps.setString(2, user);
                    int affectedRows = ps.executeUpdate();
                    if (affectedRows > 0) {
                        bo = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    JDBCUtil.close(ps, con);
                }
            } else {
                System.out.println("数据库连接失败!");
            }
        }
        return bo;
    }
}
UserDao代码:
package com.bing.dao;

import com.bing.bean.User;

public interface UserDao {
    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     * @return User
     */
    User login(String username, String password);

    /**
     * 根据用户名判断数据库里用户是否存在
     *
     * @param username 用户名
     * @return true:用户存在  false:用户不存在
     */
    boolean userExists(String username);

    /**
     * 判断是否注册成功
     *
     * @param user  用户名
     * @param pwd   密码
     * @param email 邮箱
     * @param sex   性别
     * @return true:注册失败  false:注册成功
     */
    boolean register(String user, String pwd, String email, String sex);

    /**
     * 根据数据库判断用户名和邮箱是否对应
     *
     * @param username 用户名
     * @param email    邮箱
     * @return true:用户名和邮箱对应  false:用户名和邮箱不对应
     */

    boolean userTrue(String username, String email);

    /**
     * 判断是否更改成功
     *
     * @param user  用户名
     * @param pwd   密码
     * @param email 邮箱
     * @return true:修改成功  false:修改失败
     */
    boolean change(String user, String pwd, String email);


}

dao/

impl/
UserDaoImpl代码:
package com.bing.dao.impl;

import com.bing.bean.User;
import com.bing.dao.UserDao;
import com.bing.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDaoImpl implements UserDao {
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    boolean bo = false;
    int affectedRows = 0;

    //    public UserDaoImpl() {
//        con = JDBCUtil.getCon();
//    }
    @Override
    public User login(String username, String password) {
        con = JDBCUtil.getCon();
        User login = null;

        if (con != null) {
            // 判断数据库是否连接成功
            System.out.println("login--数据库连接成功~");
            String sql = "select * from users where username = ? and pwd = ?";
            try {
                ps = con.prepareStatement(sql);
                ps.setString(1, username);
                ps.setString(2, password);
                rs = ps.executeQuery();
                // 解析结果集
                while (rs.next()) {
                    login = new User();
                    login.setUid(rs.getInt("uid"));
                    login.setUsername(rs.getString("username"));
                    login.setPassword(rs.getString("pwd"));
                    login.setEmail(rs.getString("email"));
                    login.setSex(rs.getString("sex"));
                }


            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                JDBCUtil.close(rs, ps, con);
            }

        } else {
            System.out.println("数据库连接失败!");
        }
        return login;
    }

    @Override
    public boolean userExists(String username) {
        con = JDBCUtil.getCon();
        if (con != null) {
            System.out.println("userExists--数据库连接成功~");
            String sql = "select * from users where username = ? ";
            try {
                ps = con.prepareStatement(sql);
                ps.setString(1, username);
                rs = ps.executeQuery();
                while (rs.next()) {
                    // 如果有数据,bo为true,结束循环
                    bo = true;
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                JDBCUtil.close(rs, ps, con);
            }
        } else {
            System.out.println("数据库连接失败!");
        }
        return bo;// 返回boolean值,判断是否有这个用户
    }

    @Override
    public boolean userTrue(String username, String email) {
        con = JDBCUtil.getCon();
        if (con != null) {
            System.out.println("userTrue--数据库连接成功~");
            String sql = "select * from users where username = ? and email = ?";
            try {
                ps = con.prepareStatement(sql);
                ps.setString(1, username);
                ps.setString(2, email);
                rs = ps.executeQuery();
                while (rs.next()) {
                    bo = true;
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                JDBCUtil.close(rs, ps, con);
            }
        } else {
            System.out.println("数据库连接失败!");
        }
        return bo;
    }

    @Override
    public boolean register(String user, String pwd, String email, String sex) {
        con = JDBCUtil.getCon();
        if (!userExists(user)) {
            if (con != null) {
                System.out.println("register--数据库连接成功~");
                String sql = "insert into users(username,pwd,email,sex) values(?,?,?,?) ";
                try {
                    ps = con.prepareStatement(sql);
                    ps.setString(1, user);
                    ps.setString(2, pwd);
                    ps.setString(3, email);
                    ps.setString(4, sex);
                    affectedRows = ps.executeUpdate();// 受影响的行数赋值给affectedRows
                    if (affectedRows > 0) {
                        bo = true;// 大于0则有行数受影响 数据库发生了改变 数据添加成功
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    JDBCUtil.close(ps, con);
                }

            } else {
                System.out.println("数据库连接失败!");
            }
        }
        return bo;// 返回boolean值 判断数据是否添加成功
    }


    @Override
    public boolean change(String user, String pwd, String email) {
        con = JDBCUtil.getCon();
        if (con != null) {
            System.out.println("change--数据库连接成功~");
            String sql = "update users set pwd = ? where username = ? and email = ?";
            try {
                ps = con.prepareStatement(sql);
                ps.setString(1, pwd);
                ps.setString(2, user);
                ps.setString(3, email);
                affectedRows = ps.executeUpdate();
                if (affectedRows > 0) {
                    bo = true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                JDBCUtil.close(ps, con);
            }
        } else {
            System.out.println("数据库连接失败!");
        }

        return bo;
    }

}

servlet/

Enroll代码:
package com.bing.servlet;

import com.bing.dao.EnrollDao;
import com.bing.dao.impl.UserDaoImpl;
import com.bing.util.RegexUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/enroll")
public class Enroll extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        String user = req.getParameter("userName");
        String pwd = req.getParameter("pwd");
        String email = req.getParameter("email");
        String sex = req.getParameter("sex");

        // 响应的编码
        resp.setCharacterEncoding("UTF-8");
        // 文本格式
        resp.setContentType("text/html;charset=UTF-8");
        UserDaoImpl userDao = new UserDaoImpl();
        boolean exists;// 数据库是否存在某个用户
        boolean register;// 数据是否添加成功
        boolean bo = RegexUtil.isValidEmail(email);// 判断邮箱格式
        if (bo) {// 邮箱格式正确 执行下面操作
            exists = userDao.userExists(user);
            register = userDao.register(user, pwd, email, sex);
            if (exists) {
                resp.sendRedirect("userExists.jsp");
            } else if (register) {
                resp.sendRedirect("index.jsp");
            } else {
                resp.sendRedirect("cao.jsp");
            }
        } else {
            resp.sendRedirect("illegalEmail.jsp");
        }

    }

}
Forget代码:
package com.bing.servlet;

import com.bing.dao.EnrollDao;
import com.bing.dao.ForgetDao;
import com.bing.dao.impl.UserDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/forget")
public class Forget extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String user = req.getParameter("userName");
        String pwd = req.getParameter("pwd");
        String email = req.getParameter("email");
        // 响应的编码
        resp.setCharacterEncoding("UTF-8");
        UserDaoImpl userDao = new UserDaoImpl();
        if(userDao.login(user, pwd) != null){
            resp.sendRedirect("2b.jsp");// 更改失败
        }else if(userDao.change(user, pwd, email)){
            resp.sendRedirect("changeSuccessful.jsp");// 更改成功
        }else if(!userDao.userExists(user)){
            resp.sendRedirect("userNotExists.jsp");// 用户不存在
        }else if(userDao.userTrue(user,email)){
            resp.sendRedirect("error.jsp");// 用户存在,邮箱不对
        }else {
            resp.sendRedirect("cao.jsp");// 特殊情况
        }

    }
}
Login代码:
package com.bing.servlet;

import com.bing.dao.EnrollDao;
import com.bing.dao.impl.UserDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/welcome")
public class Login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        /*
         * 处理请求源发送过来的数据
         * */
        req.setCharacterEncoding("UTF-8");// 将编码改为UTF-8
        String user = req.getParameter("userName");// user接收上个页面的userName值
        String pwd = req.getParameter("pwd");// pwd接收上个页面的pwd值
        // 响应的编码
        resp.setCharacterEncoding("UTF-8");
        // 文本格式
        resp.setContentType("text/html;charset=UTF-8");
        UserDaoImpl userDao = new UserDaoImpl();

        if (userDao.userExists(user) && userDao.login(user, pwd) == null) {
            resp.sendRedirect("forget.jsp");// 用户存在 密码不对 进入更改密码、忘记密码界面
        } else if (userDao.login(user, pwd) != null) {
            resp.sendRedirect("welcome.jsp");// 账号、密码正确  进入欢迎界面
        } else if (!userDao.userExists(user)) {
            resp.sendRedirect("enroll.jsp");// 用户不存在 注册用户
        } else {
            resp.sendRedirect("cao.jsp");// 特殊情况
        }
    }

}

util/

JDBCUtil代码:
package com.bing.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class JDBCUtil {
    private static String driver = "com.mysql.cj.jdbc.Driver";// 驱动包
    private static String url = "jdbc:mysql://localhost:3306/jwTest?useSSL=false&serverTimezone=UTC";// 数据库地址
    private static String username = "root";// 数据库账号
    private static String password = "root";// 数据库密码
    private static Connection con = null;

    public static Connection getCon() {
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return con;
    }

    public static void close(ResultSet rs, PreparedStatement ps, Connection con) {
        try {
            if (rs != null) {
                rs.close();
                System.out.println("ResultSet已释放...");
            }
            if (ps != null) {
                ps.close();
                System.out.println("PreparedStatement已释放...");
            }
            if (con != null) {
                con.close();
                System.out.println("Connection已释放...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void close(PreparedStatement ps, Connection con) {
        try {
            if (ps != null) {
                ps.close();
                System.out.println("PreparedStatement已释放...");
            }
            if (con != null) {
                con.close();
                System.out.println("Connection已释放...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
RegexUtil代码:
package com.bing.util;

import java.util.regex.Pattern;

public class RegexUtil {
    /*
     * 判断邮箱是否合法
     * */
    public static boolean isValidEmail(String email) {
        // 正则表达式
        String regex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
        // 编译正则表达式
        Pattern pattern = Pattern.compile(regex);
        // 匹配输入的邮箱地址
        return pattern.matcher(email).matches();
    }
}

三、jsp

2b.jsp代码:

<%--
  Created by IntelliJ IDEA.
  User: xbyan
  Date: 2023/2/17
  Time: 16:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<style>
    h1 {
        text-align: center;
        color: aqua;
    }

    div {
        width: 500px;
        height: 90px;
        text-align: center;
        margin: 50px auto;
    }

    button {
        width: 120px;
        height: 40px;
        border-radius: 5px;
        border: 0px;
        cursor: pointer;
    }

    #enroll:hover {
        background-color: coral;
    }
</style>
<body>
<h1>
    你的密码不就是这个?😤
</h1>
<div>
    <button value="去登录" id="enroll" onclick="window.location.href ='/myWebTest_war_exploded/index.jsp'">去登录
    </button>
</div>
</body>
</html>

cao.jsp代码:

<%--
  Created by IntelliJ IDEA.
  User: xbyan
  Date: 2023/2/16
  Time: 23:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<script>
    console.log("😤why")
</script>
<style>
  h1{
    color: red;
    text-align: center;
  }
</style>
<body>

<h1>😭😭😭😭😭😭😭😭😭😭</h1><br>
<h1>因不可控因素,操作失败!!!!!!</h1>
</body>
</html>

changeSuccessful.jsp代码:

<%--
  Created by IntelliJ IDEA.
  User: xbyan
  Date: 2023/2/16
  Time: 23:00
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>嘻嘻💕</title>
</head>
<style>
    h1 {
        text-align: center;
        color: crimson;
    }

    div {
        width: 500px;
        height: 90px;
        text-align: center;
        margin: 50px auto;
    }

    #enroll {
        margin-right: 30px;
    }
    button{
        width: 120px;
        height: 40px;
        border-radius: 5px;
        border: 0px;
        cursor: pointer;
    }
    #enroll:hover{
        background-color: coral;
    }
</style>
<body>
<h1>更改成功!</h1></br>
<div>
    <button value="去登录" id="enroll" onclick="window.location.href ='/myWebTest_war_exploded/index.jsp'">去登录</button>
</div>

</body>
</html>

enroll.jsp

<%--
  Created by IntelliJ IDEA.
  User: xbyan
  Date: 2023/2/14
  Time: 18:54
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册</title>
    <style>
        body {
            background-color: antiquewhite;
        }

        div {
            width: 370px;
            height: 400px;
            margin: auto auto;
            background-color: white;
            border-radius: 5px;
        }

        .t {
            width: 100%;
            height: 100%;
        }

        #head {
            font-family: FangSong;
            font-size: 32px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 15px;
            margin-top: 15px;
        }

        .one {
            width: 360px;
            height: 45px;
        }

        .one p {
            font-family: SimHei;
            font-size: 17px;
            text-align: right;
        }

        .one input {
            width: 210px;
            height: 45px;
            outline: none;
            border: none;
            border-bottom: 1px solid #000
        }

        .two {
            width: 120px;
            height: 45px;
        }

        .three p {
            font-family: SimHei;
            font-size: 17px;
            text-align: right;
        }

        #enroll {
            width: 330px;
            height: 45px;
            border: none;
            background-color: #ed7158;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            font-family: "Microsoft YaHei UI";
        }

        .one input:hover {
            border-color: red;
        }

        #enroll:hover {
            background-color: #d54d32;
        }
    </style>

</head>

<body>
<div>
    <form action="enroll" method="post">
        <table class="t">
            <tr>
                <td colspan="2"><p id="head">注册账号</p></td>
            </tr>
            <tr class="one">
                <td class="two"><p>账&nbsp;&nbsp;&nbsp;&nbsp;号:</p></td>
                <%--
                placeholder:用于提供有关输入字段所需内容的提示或说明
                onketup:限制中文
                pattern:限制中文个数
                required:不能为空
                --%>
                <td><input type="text" name="userName" placeholder="仅支持中文(2-6位)"
                           onkeyup="this.value=this.value.replace(/[^\u4e00-\u9fa5]/g,'')"
                           onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^/u4E00-/u9FA5]/g,''))"
                           pattern="[\u4e00-\u9fa5]{2,6}" maxlength="6">
                </td>
            </tr>
            <tr class="one">
                <td class="two"><p>密&nbsp;&nbsp;&nbsp;&nbsp;码:</p></td>
                <td><input type="password" name="pwd" id="pwd" placeholder="密码(6-16位)" minlength="6" maxlength="16">
                </td>
            </tr>
            <tr class="one">
                <td class="two"><p>确认密码:</p></td>
                <td><input type="password" name="confirmPwd" id="confirmPwd" placeholder="请再次输入密码" minlength="6" maxlength="16">
                </td>
            </tr>
            <tr class="one">
                <td class="two"><p>电子邮箱:</p></td>
                <td><input type="email" name="email" placeholder="请输入电子邮箱"></td>
            </tr>
            <tr class="three">
                <td class="two"><p>性&nbsp;&nbsp;&nbsp;&nbsp;别:</p></td>
                <td>
                    <input type="radio" name="sex" value="男">男
                    <input type="radio" name="sex" value="女">女
                </td>
            </tr>
            <tr>
                <td colspan="2" style="text-align: center">
                    <input type="submit" value="注册" id="enroll">
                </td>
            </tr>
        </table>
    </form>
</div>
<script>
    <!-- required 必须选择一个-->
    var inputs = document.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++) {
        inputs[i].required = true;
    }
    const form = document.querySelector('form');
    const password1 = document.getElementById('pwd');
    const password2 = document.getElementById('confirmPwd');

    form.addEventListener('submit', function(event) {
        if (password1.value !== password2.value) {
            alert('两次密码不同!');
            event.preventDefault();
        }
    });
</script>
</body>
</html>

error.jsp

<%--
  Created by IntelliJ IDEA.
  User: xbyan
  Date: 2023/2/16
  Time: 23:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>嘻嘻💕</title>
</head>
<style>
    h1 {
        text-align: center;
        color: crimson;
    }

    div {
        width: 500px;
        height: 90px;
        text-align: center;
        margin: 50px auto;
    }
    button{
        width: 120px;
        height: 40px;
        border-radius: 5px;
        border: 0px;
        cursor: pointer;
    }
    #enroll:hover{
        background-color: coral;
    }
</style>
<body>
<h1>邮箱与用户名不匹配,请重新更改密码</h1></br>
<h1></h1>
<div>
    <button value="更改密码" id="enroll" onclick="window.location.href ='/myWebTest_war_exploded/forget.jsp'">更改密码</button>
</div>

</body>
</html>

forget.jsp

<%--
  Created by IntelliJ IDEA.
  User: xbyan
  Date: 2023/2/14
  Time: 20:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改密码</title>
    <style>
        body {
            background-color: antiquewhite;
        }

        div {
            width: 370px;
            height: 400px;
            margin: auto auto;
            background-color: white;
            border-radius: 5px;
        }

        .t {
            width: 100%;
            height: 100%;
        }

        #head {
            font-family: FangSong;
            font-size: 32px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 15px;
            margin-top: 15px;
        }

        .one {
            width: 360px;
            height: 45px;
        }

        .one p {
            font-family: SimHei;
            font-size: 17px;
            text-align: right;
        }

        .one input {
            width: 210px;
            height: 45px;
            outline: none;
            border: none;
            border-bottom: 1px solid #000
        }

        .two {
            width: 120px;
            height: 45px;
        }


        #enroll {
            width: 330px;
            height: 45px;
            border: none;
            background-color: #ed7158;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            font-family: "Microsoft YaHei UI";
        }

        .one input:hover {
            border-color: red;
        }

        #enroll:hover {
            background-color: #d54d32;
        }
    </style>

</head>
<body>
<div>
    <form action="forget" method="post">
        <table class="t">
            <tr>
                <td colspan="2"><p id="head">修改密码</p></td>
            </tr>
            <tr class="one">
                <td class="two"><p>账&nbsp;&nbsp;&nbsp;&nbsp;号:</p></td>
                <td><input type="text" name="userName" onkeyup="this.value=this.value.replace(/[^\u4e00-\u9fa5]/g,'')"
                           onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^/u4E00-/u9FA5]/g,''))"
                           pattern="[\u4e00-\u9fa5]{2,6}" maxlength="6"
                           placeholder="仅支持中文(2-6位)">
                </td>
            </tr>
            <tr class="one">
                <td class="two"><p>密&nbsp;&nbsp;&nbsp;&nbsp;码:</p></td>
                <td><input type="password" name="pwd" id = "pwd" placeholder="密码(6-16位)" minlength="6" maxlength="16">
                </td>
            </tr>
            <tr class="one">
                <td class="two"><p>确认密码:</p></td>
                <td><input type="password" name="confirmPwd" id = "confirmPwd" placeholder="请再次输入密码" minlength="6" maxlength="16">
                </td>
            </tr>
            <tr class="one">
                <td class="two"><p>电子邮箱:</p></td>
                <td><input type="email" name="email" placeholder="请输入电子邮箱"></td>
            </tr>
            <tr>
                <td colspan="2" style="text-align: center">
                    <input type="submit" value="更改" id="enroll">
                </td>
            </tr>
        </table>
    </form>
</div>
<script>
    <!-- required 必须选择一个-->
    var inputs = document.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++) {
        inputs[i].required = true;
    }
    const form = document.querySelector('form');
    const password1 = document.getElementById('pwd');
    const password2 = document.getElementById('confirmPwd');

    form.addEventListener('submit', function(event) {
        if (password1.value !== password2.value) {
            alert('两次密码不同!');
            event.preventDefault();
        }
    });
</script>
</body>
</html>

illgalEmail.jsp

<%--
  Created by IntelliJ IDEA.
  User: xbyan
  Date: 2023/2/16
  Time: 23:32
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<style>
    h1 {
        color: red;
        text-align: center;
    }

    div {
        width: 500px;
        height: 90px;
        text-align: center;
        margin: 50px auto;
    }

    button {
        width: 120px;
        height: 40px;
        border-radius: 5px;
        border: 0px;
        cursor: pointer;
    }

    #enroll:hover {
        background-color: coral;
    }
</style>
<body>
<h1>你邮箱是这个?请输入正确的邮箱。3q🤗</h1></br>
<button value="重新注册" id="enroll" onclick="window.location.href ='/myWebTest_war_exploded/enroll.jsp'">重新注册
</button>
</body>
</html>

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: xbyan
  Date: 2023/2/14
  Time: 16:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Ybb778</title>
</head>
<style>
    body {
        background-image: url("image/bkgd.jpg");
        background-size: 100% 100%;
    }

    p {
        font-family: FangSong;
        font-size: 40px;
        font-weight: bold;
        text-align: center;
        margin-top: 18px;
        margin-bottom: 10px;
    }

    .biao {
        width: 450px;
        height: 300px;
        margin: auto auto;
        background-color: white;
        border-radius: 5px;
    }

    tr {
        width: 400px;
        height: 40px;
        border: 0;
    }

    .one input {
        width: 400px;
        height: 35px;
        outline: none;
        border: none;
        border-bottom: 1px solid #000
    }

    .t {
        width: 100%;
        height: 100%;
    }

    .one {
        text-align: center;
    }

    #two {
        border: none;
        background-color: #ed7158;
        border-radius: 5px;
        font-size: 16px;
        font-family: "Microsoft YaHei UI";
        cursor: pointer;
    }

    .three {
        text-align: center;
    }

    .four {
        text-decoration: none;
        color: #696969;
    }

    .five {
        color: #C0C0C0;
    }

    .one input:hover {
        border-color: red;
    }

    .four:hover {
        color: #383030;
    }

    #two:hover {
        background-color: #d54d32;
    }
</style>

<body>
<div class="biao">
    <form action="welcome" method="post">
        <table class="t">
            <tr>
                <td><p>无聊</p></td>
            </tr>
            <tr>
                <td class="one"><input type="text" name="userName" placeholder="账号(中文)"
                                       onkeyup="this.value=this.value.replace(/[^\u4e00-\u9fa5]/g,'')"
                                       onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^/u4E00-/u9FA5]/g,''))"
                                       pattern="[\u4e00-\u9fa5]{2,6}" maxlength="6">
                </td>
            </tr>
            <tr>
                <td class="one"><input type="password" name="pwd" placeholder="密码(6-16位)" minlength="6"
                                       maxlength="16">
                </td>
            </tr>
            <tr>
                <td class="one"><input type="submit" value="登录" id="two"></td>
            </tr>
            <tr>
                <td class="three"><a href="enroll.jsp" class="four">注册账号</a><a class="five">丨</a><a
                        href="forget.jsp" class="four">忘记密码</a></td>
            </tr>
        </table>
    </form>
</div>
<script>
    <!-- required 必须选择一个-->
    var inputs = document.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++) {
        inputs[i].required = true;
    }
</script>
</body>
</html>

userExists.jsp

<%--
  Created by IntelliJ IDEA.
  User: xbyan
  Date: 2023/2/16
  Time: 21:44
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>嘻嘻💕</title>
</head>
<style>
    h1 {
        text-align: center;
        color: crimson;
    }

    div {
        width: 500px;
        height: 90px;
        text-align: center;
        margin: 50px auto;
    }

    #enroll {
        margin-right: 30px;
    }
    button{
        width: 120px;
        height: 40px;
        border-radius: 5px;
        border: 0px;
        cursor: pointer;
    }
    #enroll:hover{
        background-color: coral;
    }
    #forget:hover{
        background-color: aquamarine;
    }
</style>
<body>
<h1>该用户已存在!</h1>
<div>
    <button value="重新注册" id="enroll" onclick="window.location.href ='/myWebTest_war_exploded/enroll.jsp'">重新注册</button>
    <button value="更改密码" id="forget" onclick="window.location.href ='/myWebTest_war_exploded/forget.jsp'">忘记密码</button>
</div>

</body>
</html>

userNotExists.jsp

<%--
  Created by IntelliJ IDEA.
  User: xbyan
  Date: 2023/2/16
  Time: 22:54
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>嘻嘻💕</title>
</head>
<style>
    h1 {
        text-align: center;
        color: crimson;
    }

    div {
        width: 500px;
        height: 90px;
        text-align: center;
        margin: 50px auto;
    }

    #enroll {
        margin-right: 30px;
    }
    button{
        width: 120px;
        height: 40px;
        border-radius: 5px;
        border: 0px;
        cursor: pointer;
    }
    #enroll:hover{
        background-color: coral;
    }
</style>
<body>
<h1>此用户不存在!</h1></br>
<h1></h1>
<div>
    <button value="重新注册" id="enroll" onclick="window.location.href ='/myWebTest_war_exploded/enroll.jsp'">去注册</button>
</div>

</body>
</html>

welcome.jsp

<%--
  Created by IntelliJ IDEA.
  User: xbyan
  Date: 2023/2/16
  Time: 12:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>welcome</title>
</head>
<style>
    h1{
        color: orange;
        text-align: center;
    }
</style>
<body>
<h1>欢迎你😊😍😘🥰🤗</h1>
</body>
</html>

  • 23
    点赞
  • 193
    收藏
    觉得还不错? 一键收藏
  • 15
    评论
实现JavaWeb登录连接数据库,需要以下步骤: 1. 导入JDBC驱动包:在项目中导入MySQL JDBC驱动包,可以从MySQL官网或者Maven仓库下载。 2. 创建数据库和数据表:创建一个用户表,包含id、username、password等字段。 3. 创建JDBC连接:通过JDBC连接数据库,使用JDBCUtils类封装JDBC连接的操作,获取数据库连接。 4. 编写登录逻辑:获取用户输入的用户名和密码,查询数据库中是否存在该用户,若存在则登录成功,否则登录失败。 下面是一个简单的JavaWeb登录连接数据库的示例代码: ``` // 导入JDBC驱动包和JDBCUtils类 import java.sql.*; import com.utils.JDBCUtils; public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取用户输入的用户名和密码 String username = request.getParameter("username"); String password = request.getParameter("password"); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { // 获取数据库连接 conn = JDBCUtils.getConnection(); // 编写SQL语句,查询用户是否存在 String sql = "select * from user where username=? and password=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, username); pstmt.setString(2, password); rs = pstmt.executeQuery(); if (rs.next()) { // 若存在则登录成功 request.getRequestDispatcher("success.jsp").forward(request, response); } else { // 否则登录失败 request.getRequestDispatcher("fail.jsp").forward(request, response); } } catch (SQLException e) { e.printStackTrace(); } finally { // 关闭数据库连接 JDBCUtils.release(conn, pstmt, rs); } } } ``` 需要注意的是,JDBCUtils类需要根据具体的数据库配置进行修改,例如数据库的URL、用户名和密码等。
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值