上一篇博客中我通过使用HttpServlet完成一个假登录,这篇博客我将通过JDBC连接数据库,使其实现简单的用户登录、注册以及更改密码
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', '[email protected]', '男');
INSERT INTO `users` VALUES (1003, '李四', '123000', '[email protected]', '男');
INSERT INTO `users` VALUES (1004, '马冬梅', '123456', '[email protected]', '女');
bean/User存放用户的实体类,实现了序列化接口,定义私有属性,set,get方法的普通java类
dao/impl/UserDao 接口,声明所需要的所有方法
dao/impl/UserDaoImpl 用在和数据直接交互,比如常用的是定义交互数据库的类或接口
servlet/Enroll 继承HttpServlet类,重写doGet方法和doPost方法,接收注册信息
servlet/Forget 更改密码
servlet/Login 登录
util/JDBCUtil 连接数据库
util/RegexUtil 判断邮箱格式
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 + '\'' +
'}';
}
}
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值 判断数据是否添加成功
}
}
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;
}
}
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);
}
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;
}
}
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");
}
}
}
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");// 特殊情况
}
}
}
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");// 特殊情况
}
}
}
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();
}
}
}
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();
}
}
<%--
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" %>
Title
你的密码不就是这个?
<%--
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" %>
Title
因不可控因素,操作失败!!!!!!
<%--
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" %>
嘻嘻
更改成功!
<%--
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" %>
注册
<%--
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" %>
嘻嘻
邮箱与用户名不匹配,请重新更改密码
<%--
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" %>
修改密码
<%--
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" %>
Title
你邮箱是这个?请输入正确的邮箱。3q
<%--
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" %>
Ybb778
<%--
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" %>
嘻嘻
该用户已存在!
<%--
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" %>
嘻嘻
此用户不存在!
<%--
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" %>
welcome
欢迎你