![登录页面](https://i-blog.csdnimg.cn/blog_migrate/c7512ddf723cc2599376f42d67729c8f.png)
![](https://i-blog.csdnimg.cn/blog_migrate/fab4127f8971507148c117667962cb16.png)
数据库
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`password` varchar(32) NOT NULL,
`phone` varchar(11) DEFAULT NULL COMMENT '手机号',
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
后端操作
JdbcUtils.java
import java.sql.*;
/**
* 2023/12/30
*/
public class JdbcUtils {
private final static String URL = "jdbc:mysql://localhost:3306/web?useUnicode=true&characterEncoding=utf-8";
private final static String USER = "root";
private final static String PASSWORD = "123456";
private final static String DRIVER = "com.mysql.jdbc.Driver";
private static Connection conn = null;
public static Statement stmt = null;
public static ResultSet rs = null;
/**
* 获取数据库连接
*/
public static Connection getConnection() {
try {
// 加载驱动
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (Exception e) {
System.out.println("数据库连接异常");
e.printStackTrace();
}
return conn;
}
/**
* 功能:执行查询操作
*/
public static ResultSet executeQuery(String sql) {
try {
conn = getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return rs;
}
/*
* 功能:执行更新操作
*/
public static int executeUpdate(String sql) {
int result = 0;
try {
//调用getConnection()方法构造Connection对象的一个实例conn
conn = getConnection();
stmt = conn.createStatement();
//执行更新操作
result = stmt.executeUpdate(sql);
} catch (SQLException ex) {
result = 0;
}
return result;
}
/*
* 功能:关闭数据库的连接
*/
public static void close() {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
UserDao.java
import com.web.pojo.User;
import com.web.utils.JdbcUtils;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 2023/12/30
*/
public class UserDao {
public User login(String username, String password) {
String sql = String.format("select * from user where username='%s' and password = '%s'", username, password);
ResultSet resultSet = JdbcUtils.executeQuery(sql);
User user = new User();
try {
if (resultSet.next()) {
user.setId(resultSet.getInt(1));
user.setUsername(username);
user.setPassword(password);
user.setPhone(resultSet.getString(4));
} else {
user = null;
}
} catch (SQLException ignored) {
}
JdbcUtils.close();
return user;
}
public Integer register(String username, String password, String phone) {
String sql = String.format("INSERT INTO user (username, password, phone) VALUES ('%s', '%s', '%s')", username, password, phone);
Integer num = JdbcUtils.executeUpdate(sql);
JdbcUtils.close();
return num;
}
public Integer updatePassword(Integer id, String password) {
String sql = String.format("update user set password='%s' where id = %d", password, id);
Integer num = JdbcUtils.executeUpdate(sql);
JdbcUtils.close();
return num;
}
public Integer queryCountByUsername(String username) {
String sql = String.format("select count(*) from user where username='%s'", username);
ResultSet resultSet = JdbcUtils.executeQuery(sql);
Integer count = 0;
try {
if (resultSet.next()) {
count = resultSet.getInt(1);
}
} catch (SQLException ignored) {
}
JdbcUtils.close();
return count;
}
}
UserService.java
import com.web.config.Constant;
import com.web.dao.UserDao;
import com.web.pojo.Message;
import com.web.pojo.User;
/**
* 2023/12/30
*/
public class UserService {
public User login(String username, String password) {
User user = null;
if (username == null || "".equals(username)) {
return user;
}
if (password == null || "".equals(password)) {
return user;
}
return new UserDao().login(username, password);
}
public Message register(String username, String password, String phone) {
if (username == null || "".equals(username)) {
return new Message(Constant.FAIL, "注册失败,用户名不能为空");
}
if (password == null || "".equals(password)) {
return new Message(Constant.FAIL, "注册失败,密码不能为空");
}
if (!isValidPhoneNumber(phone)) {
return new Message(Constant.FAIL, "注册失败,手机号格式正确");
}
UserDao userDao = new UserDao();
Integer countByUsername = userDao.queryCountByUsername(username);
if (countByUsername>0){
return new Message(Constant.FAIL, "注册失败,用户名已存在");
}
Integer register = userDao.register(username, password, phone);
if (register > 0) {
return new Message(Constant.SUCCESS, "注册成功");
} else {
return new Message(Constant.FAIL, "注册失败");
}
}
public Message updatePassword(String oldPassword,String password,String confirmPassword,User user){
if (user == null){
return new Message(Constant.FAIL,"修改密码失败,请先登录");
}
if (!oldPassword.equals(user.getPassword())){
return new Message(Constant.FAIL,"修改密码失败,旧密码不正确");
}
if (!password.equals(confirmPassword)){
return new Message(Constant.FAIL,"修改密码失败,密码和确认密码不一致");
}
Integer result = new UserDao().updatePassword(user.getId(), password);
if (result > 0) {
return new Message(Constant.SUCCESS, "修改密码成功");
} else {
return new Message(Constant.FAIL, "修改密码失败");
}
}
private boolean isValidPhoneNumber(String phone) {
if (phone == null) {
return false;
}
// 简单的手机号验证,实际项目中应该使用更严格的验证方法
return phone.matches("^1\\d{10}$");
}
}
User.java
public class User {
private Integer id;
private String username;
private String password;
private String phone;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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 getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Message.java
public class Message {
private Integer type;
private String msg;
public Message() {
}
public Message(Integer type, String msg) {
this.type = type;
this.msg = msg;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
WebServlet.java
import com.web.config.Constant;
import com.web.pojo.Message;
import com.web.pojo.User;
import com.web.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* 2023/12/30
*/
@WebServlet("/UserServlet")
public class UserServlet extends BaseServlet {
/**
* 登录
*/
public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = new UserService().login(username, password);
if (user == null) {
request.setAttribute("message", new Message(Constant.FAIL, "登录失败,用户名或密码错误!"));
request.getRequestDispatcher("login.jsp").forward(request, response);
} else {
HttpSession session = request.getSession();
session.setAttribute("user", user);
request.setAttribute("message", new Message(Constant.SUCCESS, "登录成功!"));
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
/**
* 注册
*/
public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String phone = request.getParameter("phone");
Message message = new UserService().register(username, password, phone);
request.setAttribute("message", message);
if (Constant.SUCCESS.equals(message.getType())){
request.getRequestDispatcher("login.jsp").forward(request, response);
}else{
request.getRequestDispatcher("register.jsp").forward(request, response);
}
}
/**
* 修改密码
*/
public void updatePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String confirmPassword = request.getParameter("confirmPassword");
String password = request.getParameter("password");
String oldPassword = request.getParameter("oldPassword");
User user = (User)request.getSession().getAttribute("user");
Message message = new UserService().updatePassword(oldPassword,password,confirmPassword,user);
request.setAttribute("message", message);
request.getRequestDispatcher("updatePassword.jsp").forward(request, response);
}
public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.removeAttribute("user");
request.setAttribute("message", new Message(Constant.SUCCESS, "退出登录成功!"));
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
BaseServlet.java
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
/**
* 2023/12/30
*/
public class BaseServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
String action = request.getParameter("action");
try {
Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
method.invoke(this, request, response);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
Constant.java
public class Constant {
public static final Integer SUCCESS = 200;
public static final Integer FAIL = 101;
}
页面操作
header.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- 引入 Bootstrap 的 CSS 文件 -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
background-color: #f8f9fa;
}
/* 侧边栏样式 */
.sidebar {
height: 100%;
width: 250px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #007bff;
padding-top: 20px;
color: #fff;
}
.sidebar a {
padding: 15px 20px;
font-size: 18px;
text-decoration: none;
display: block;
color: #fff;
transition: 0.3s;
}
.sidebar a:hover {
background-color: beige;
margin-left: -12px;
margin-right: -12px;
}
.sidebar-heading {
font-size: 24px;
font-weight: bold;
margin-bottom: 20px;
}
/* 主内容区域 */
.active {
background: dodgerblue;
margin-right: -12px;
margin-left: -12px;
}
</style>
</head>
<%String flag = request.getParameter("flag");%>
<body>
<div class="container-fluid">
<div class="row">
<!-- 侧边栏 -->
<nav class="col-md-2 d-none d-md-block sidebar">
<div class="sidebar-sticky">
<h1 class="sidebar-heading">后台操作系统</h1>
<ul class="nav flex-column">
<%if (flag.equals("1")) {%>
<li class="nav-item"><a href="index.jsp" class="active nav-link">个人中心</a></li>
<%} else {%>
<li class="nav-item"><a class="nav-link" href="index.jsp">个人中心</a></li>
<%}%>
<%if (flag.equals("2")) {%>
<li class="nav-item"><a href="updatePassword.jsp" class="active nav-link">修改密码</a></li>
<%} else {%>
<li class="nav-item"><a class="nav-link" href="updatePassword.jsp">修改密码</a></li>
<%}%>
<li class="nav-item">
<a class="nav-link" href="UserServlet?action=logout">退出登录</a>
</li>
</ul>
</div>
</nav>
</div>
</div>
</body>
</html>
index.jsp
<%@ page import="com.web.pojo.User" %>
<%@ page import="java.util.Objects" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<title>后台管理</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
background-color: #f8f9fa;
}
.auth-container {
margin-top: 50px;
width: 60%!important;
}
.auth-switch a {
color: #007bff;
}
.auth-switch a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div class="container auth-container">
<jsp:include page="header.jsp">
<jsp:param name="flag" value="1"/>
</jsp:include>
<h2 class="mb-4">欢迎登录</h2>
<%-- 获取用户信息 --%>
<% User user = (User) session.getAttribute("user"); %>
<%-- 判断用户是否登录 --%>
<% if (Objects.nonNull(user)) { %>
<div class="card">
<div class="card-body">
<h5 class="card-title">欢迎登录, <%= user.getUsername() %>
</h5>
<p class="card-text">编号: <%= user.getId() %>
<p class="card-text">姓名: <%= user.getUsername() %>
<p class="card-text">手机号: <%= user.getPhone() %>
</p>
<%-- 在这里展示其他用户信息 --%>
</div>
</div>
<% } else { %>
<%-- 用户未登录,重定向到登录页面 --%>
<script>
window.location.href = 'login.jsp';
</script>
<% } %>
</div>
</body>
</html>
login.jsp
<%@ page import="com.web.config.Constant" %>
<%@ page import="com.web.pojo.Message" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false" %>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>用户登录</title>
<!-- 引入 Bootstrap 样式表 -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
background-color: #f8f9fa;
}
.auth-container {
margin-top: 50px;
}
.auth-card {
border: none;
border-radius: 15px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.auth-card-header {
background-color: #007bff;
color: #fff;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
}
.auth-btn {
border-radius: 15px;
}
.auth-btn-primary {
background-color: #007bff;
color: #fff;
}
.auth-btn-primary:hover {
background-color: #0056b3;
}
.auth-switch {
text-align: center;
margin-top: 10px;
}
.auth-switch a {
color: #007bff;
}
.auth-switch a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<% Message message = (Message) request.getAttribute("message");%>
<div class="container auth-container">
<div class="row justify-content-center">
<div class="col-md-4">
<%if (message != null && Constant.SUCCESS.equals(message.getType())) {%>
<div class="alert alert-success"><%=message.getMsg()%>
</div>
<%} else if (message != null && Constant.FAIL.equals(message.getType())) {%>
<div class="alert alert-danger"><%=message.getMsg()%>
</div>
<%}%>
<div class="card auth-card">
<div class="card-header text-center auth-card-header">
<h3>登录</h3>
</div>
<div class="card-body">
<!-- 登录表单 -->
<form method="post" action="UserServlet?action=login">
<div class="mb-3">
<label for="username" class="form-label">用户名</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">密码</label>
<input type="password" class="form-control" id="password" name="password"
required>
</div>
<div class="mb-3" style="text-align: center">
<button type="submit" class="btn btn-primary btn-block auth-btn auth-btn-primary">登录
</button>
</div>
</form>
<div class="auth-switch">
<p>没有账号? <a href="register.jsp">注册</a></p>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
register.jsp
<%@ page import="com.web.config.Constant" %>
<%@ page import="com.web.pojo.Message" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false" %>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>用户注册</title>
<!-- 引入 Bootstrap 样式表 -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
background-color: #f8f9fa;
}
.auth-container {
margin-top: 50px;
}
.auth-card {
border: none;
border-radius: 15px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.auth-card-header {
background-color: #007bff;
color: #fff;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
}
.auth-btn {
border-radius: 15px;
}
.auth-btn-primary {
background-color: #007bff;
color: #fff;
}
.auth-btn-primary:hover {
background-color: #0056b3;
}
.auth-switch {
text-align: center;
margin-top: 10px;
}
.auth-switch a {
color: #007bff;
}
.auth-switch a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<% Message message = (Message) request.getAttribute("message");%>
<div class="container auth-container">
<div class="row justify-content-center">
<div class="col-md-4">
<%if (message != null && Constant.SUCCESS.equals(message.getType())) {%>
<div class="alert alert-success"><%=message.getMsg()%>
</div>
<%} else if (message != null && Constant.FAIL.equals(message.getType())) {%>
<div class="alert alert-danger"><%=message.getMsg()%>
</div>
<%}%>
<div class="card auth-card">
<div class="card-header text-center auth-card-header">
<h3>注册</h3>
</div>
<div class="card-body">
<form method="post" action="UserServlet?action=register">
<div class="mb-3">
<label for="username" class="form-label">用户名</label>
<input type="text" class="form-control" id="username" name="username"
required>
</div>
<div class="mb-3">
<label for="password" class="form-label">密码</label>
<input type="password" class="form-control" id="password" name="password"
required>
</div>
<div class="mb-3">
<label for="phone" class="form-label">手机号</label>
<input type="text" class="form-control" id="phone" name="phone" required>
</div>
<div class="mb-3" style="text-align: center">
<button type="submit" class="btn btn-primary btn-block auth-btn auth-btn-primary">注册
</button>
</div>
</form>
<div class="auth-switch">
<p>已经有账号? <a href="login.jsp" id="login-link">登录</a></p>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
updatePassword.jsp
<%@ page import="com.web.config.Constant" %>
<%@ page import="com.web.pojo.Message" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>修改密码</title>
<!-- 引入 Bootstrap 的 CSS 文件 -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
background-color: #f8f9fa;
}
.auth-container {
margin-top: 50px;
}
.auth-card {
border: none;
border-radius: 15px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.auth-card-header {
background-color: #007bff;
color: #fff;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
}
.auth-btn {
border-radius: 15px;
}
.auth-btn-primary {
background-color: #007bff;
color: #fff;
}
.auth-btn-primary:hover {
background-color: #0056b3;
}
.auth-switch {
text-align: center;
margin-top: 10px;
}
.auth-switch a {
color: #007bff;
}
.auth-switch a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<% Message message = (Message) request.getAttribute("message");%>
<div class="container auth-container">
<jsp:include page="header.jsp">
<jsp:param name="flag" value="2"/>
</jsp:include>
<div class="row justify-content-center">
<div class="col-md-4">
<%if (message != null && Constant.SUCCESS.equals(message.getType())) {%>
<div class="alert alert-success"><%=message.getMsg()%>
</div>
<%} else if (message != null && Constant.FAIL.equals(message.getType())) {%>
<div class="alert alert-danger"><%=message.getMsg()%>
</div>
<%}%>
<div class="card auth-card">
<div class="card-header text-center auth-card-header">
<h3>修改密码</h3>
</div>
<div class="card-body">
<form action="UserServlet?action=updatePassword" method="post">
<div class="form-group">
<label for="oldPassword">旧密码:</label>
<input type="password" class="form-control" id="oldPassword" name="oldPassword" required>
</div>
<div class="form-group">
<label for="password">新密码:</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<div class="form-group">
<label for="confirmPassword">确认密码:</label>
<input type="password" class="form-control" id="confirmPassword" name="confirmPassword" required>
</div>
<br>
<div class="mb-3" style="text-align: center">
<button type="submit" class="btn btn-primary btn-block auth-btn auth-btn-primary">提交
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>