如何自主建设企业网站网址之家大全
简介
本教程将指导您如何使用Java Servlet和JSP技术构建一个简单的Web应用程序。该应用程序将包括用户注册、登录、注销(删除用户信息)、修改密码以及根据性别查询用户信息等功能。我们将使用MySQL数据库来存储用户数据。
环境准备
- Java Development Kit (JDK): 安装JDK 8或更高版本。
- IDE: 推荐使用IntelliJ IDEA或Eclipse。
- Servlet容器: 如Apache Tomcat 9或更高版本。
- MySQL数据库: 安装并运行MySQL服务。
步骤 1: 设置数据库
- 打开MySQL命令行工具。
- 创建数据库
student
。 - 执行
t.jsp
中的SQL语句创建info
表。
<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>创建表并插入数据</title>
</head>
<body>
<%Connection conn = null;Statement stmt = null;try {// 加载 MySQL JDBC 驱动程序Class.forName("com.mysql.cj.jdbc.Driver");// 创建数据库连接conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", "root", "123456");// 创建 Statement 对象stmt = conn.createStatement();// 创建表的 SQL 语句String createTableSql = "CREATE TABLE IF NOT EXISTS info (" +"id INT AUTO_INCREMENT PRIMARY KEY, " +"name VARCHAR(255) NOT NULL, " +"email VARCHAR(255) NOT NULL, " +"age INT NOT NULL, " +"gender VARCHAR(10) NOT NULL, " +"password VARCHAR(255) NOT NULL, " +"hobbies VARCHAR(255), " +"introduction TEXT" +")";// 执行创建表的 SQL 语句stmt.executeUpdate(createTableSql);out.println("表创建成功!");// 插入数据的 SQL 语句String insertSql = "INSERT INTO info (name, email, age, gender, password, hobbies, introduction) " +"VALUES ('John Doe', 'john.doe@example.com', 22, 'Male', 'password123', 'Reading, Hiking', 'A passionate learner and explorer.')";// 执行插入数据的 SQL 语句int affectedRows = stmt.executeUpdate(insertSql);if (affectedRows > 0) {out.println("数据插入成功!");} else {out.println("数据插入失败!");}} catch (Exception e) {out.println("数据库错误: " + e.getMessage());} finally {// 关闭 Statement 和 Connection 对象try {if (stmt != null) stmt.close();} catch (SQLException se2) {// 忽略关闭错误}try {if (conn != null) conn.close();} catch (SQLException se) {// 忽略关闭错误}}
%>
</body>
</html>
步骤 2: 创建项目和配置环境
- 在IDE中创建一个新的Java Web项目。
- 配置项目的构建路径,包括JDK和Servlet API库。
步骤 3: 实现数据库连接
- 在
DBConnection.java
中配置数据库连接参数。
package import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;public class DBConnection {private static final String DRIVER = "com.mysql.cj.jdbc.Driver";private static final String URL = "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC";private static final String USERNAME = "root";private static final String PASSWORD = "123456";/*** 获取数据库连接* @return 数据库连接对象*/public static Connection getConnection() {Connection conn = null;try {// 加载 MySQL JDBC 驱动程序Class.forName(DRIVER);// 创建数据库连接conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);System.out.println("MySQL JDBC driver is loaded and connection is established.");} catch (ClassNotFoundException e) {System.out.println("MySQL JDBC driver is not found.");e.printStackTrace();} catch (SQLException e) {System.out.println("Failed to establish a database connection.");e.printStackTrace();}return conn;}
}
- 实现
getConnection
方法,用于获取数据库连接。
步骤 4: 实现业务逻辑
- 用户注册: 在
RegServlet.java
中实现用户注册逻辑。
package ;import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;@WebServlet("/RegServlet")
public class RegServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String name = request.getParameter("name");String email = request.getParameter("email");String password = request.getParameter("password");String gender = request.getParameter("gender");String ageStr = request.getParameter("age");String[] hobbiesArray = request.getParameterValues("hobby"); // 兴趣爱好可能有多个String introduction = request.getParameter("introduction");// 将爱好数组转换为由逗号分隔的字符串String hobbies = (hobbiesArray != null) ? String.join(", ", hobbiesArray) : "";Student student = new Student();student.setName(name);student.setEmail(email);student.setGender(gender);student.setPassword(password);student.setAge(Integer.parseInt(ageStr)); // 确保 age 参数可以转换为整数student.setHobbies(hobbies);student.setIntroduction(introduction);StudentDAO studentDAO = new StudentDAO(); // 使用 StudentDAO 来处理业务逻辑Result result = studentDAO.insertStudent(student); // 调用 insertStudent 方法if (result.isSuccess()) { response.sendRedirect("login.jsp");} else {response.sendRedirect("error.jsp");}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 可以选择显示注册表单或者重定向到注册页面response.sendRedirect("index.jsp");}
}
- 用户登录: 在
LoginServlet.java
中实现用户登录逻辑。
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;import cn.edu.hbcit.dml.DBConnection;@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String email = request.getParameter("email");String password = request.getParameter("password");Connection conn = null; // 将 conn 声明移动到 try 块外部try {conn = DBConnection.getConnection();PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM info WHERE email=? AND password=?");pstmt.setString(1, email);pstmt.setString(2, password);ResultSet rs = pstmt.executeQuery();if (rs.next()) {HttpSession session = request.getSession();session.setAttribute("user", rs.getString("name"));session.setAttribute("userEmail", email); // 存储用户邮箱到会话session.setAttribute("userPassword", password); // 存储用户密码到会话response.sendRedirect("home.jsp");} else {response.sendRedirect("login.jsp?error=invalidCredentials");}} catch (SQLException e) {e.printStackTrace();response.sendRedirect("login.jsp?error=databaseError");} finally {try {if (conn != null) conn.close();} catch (SQLException ex) {ex.printStackTrace();}}}
}
- 注销: 在
DelServlet.java
中实现注销逻辑。
package import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;import Student;public class DelStudent {private static final Logger logger = Logger.getLogger(DelStudent.class.getName());/*** 根据邮箱和密码删除学生信息的方法。* @param student 包含要删除的学生信息的对象* @return 操作结果,包含是否成功和消息*/public Result deleteStudent(Student student) {String sql = "DELETE FROM info WHERE email = ? AND password = ?"; // 删除语句try (Connection conn = DBConnection.getConnection(); // 直接使用静态方法获取连接PreparedStatement pstmt = conn.prepareStatement(sql)) {// 设置 PreparedStatement 参数为邮箱和密码pstmt.setString(1, student.getEmail());pstmt.setString(2, student.getPassword());// 执行删除操作int affectedRows = pstmt.executeUpdate();if (affectedRows > 0) {logger.log(Level.INFO, "数据删除成功,影响行数:{0}", affectedRows);System.out.println("删除成功,影响行数:" + affectedRows); // 输出到控制台return new Result(true, "删除成功");} else {logger.log(Level.WARNING, "删除失败,没有行受到影响");System.out.println("删除失败,没有行受到影响"); // 输出到控制台return new Result(false, "删除失败");}} catch (SQLException e) {logger.log(Level.SEVERE, "数据库错误: " + e.getMessage(), e);System.out.println("数据库错误: " + e.getMessage()); // 输出到控制台return new Result(false, "数据库错误: " + e.getMessage());}}
}
- 修改密码: 实现
ChangePasswordServlet.java
。
package import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;import DBConnection;@WebServlet("/ChangePasswordServlet")
public class ChangePasswordServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String email = request.getParameter("email");String oldPassword = request.getParameter("oldPassword");String newPassword = request.getParameter("newPassword");String confirmPassword = request.getParameter("confirmPassword");// 检查新密码是否输入一致if (!newPassword.equals(confirmPassword)) {request.setAttribute("error", "新密码不匹配");request.getRequestDispatcher("changePassword.jsp").forward(request, response);return;}// 获取数据库连接Connection conn = DBConnection.getConnection();// 验证旧密码try {PreparedStatement pstmt = conn.prepareStatement("SELECT password FROM info WHERE email = ?");pstmt.setString(1, email);ResultSet rs = pstmt.executeQuery();if (rs.next() && rs.getString("password").equals(oldPassword)) {// 旧密码正确,更新新密码PreparedStatement updatePstmt = conn.prepareStatement("UPDATE info SET password = ? WHERE email = ?");updatePstmt.setString(1, newPassword);updatePstmt.setString(2, email);int affectedRows = updatePstmt.executeUpdate();if (affectedRows > 0) {// 密码更新成功,重定向到登录页面response.sendRedirect("login.jsp?message=密码修改成功");} else {// 密码更新失败request.setAttribute("error", "密码更新失败");request.getRequestDispatcher("changePassword.jsp").forward(request, response);}} else {// 旧密码错误或用户不存在request.setAttribute("error", "旧密码错误或用户不存在");request.getRequestDispatcher("changePassword.jsp").forward(request, response);}} catch (SQLException e) {throw new ServletException("数据库错误: " + e.getMessage());} finally {try {if (conn != null) conn.close();} catch (SQLException ex) {ex.printStackTrace();}}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 重定向到修改密码表单页面response.sendRedirect("login.jsp");}
}
- 查询用户信息: 实现
QueryServlet.java
。
package ;import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;import Student;@WebServlet("/QueryServlet")
public class QueryServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();String sex = request.getParameter("sex");System.out.print("查询性别: " + sex);ArrayList<Student> students = new ArrayList<>();try (Connection conn = DBConnection.getConnection();PreparedStatement pstmt = conn.prepareStatement("SELECT name, email, age, gender, hobbies, introduction FROM info WHERE gender = ?")) {pstmt.setString(1, sex);ResultSet rs = pstmt.executeQuery();while (rs.next()) {Student student = new Student();student.setName(rs.getString("name"));student.setEmail(rs.getString("email"));student.setAge(rs.getInt("age"));student.setGender(rs.getString("gender"));student.setHobbies(rs.getString("hobbies"));student.setIntroduction(rs.getString("introduction"));students.add(student);}} catch (SQLException e) {e.printStackTrace();out.println("数据库错误: " + e.getMessage());}request.setAttribute("students", students);request.getRequestDispatcher("QueryResult.jsp").forward(request, response);}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}
}
步骤 5: 创建用户界面
- 注册页面: 创建
index.jsp
。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head><title>用户注册页面</title><style>body {font-family: Arial, sans-serif;display: flex;justify-content: center;align-items: center;height: 100vh;margin: 0;background-color: #fff;}.background-image {position: fixed;bottom: 0;left: 0;width: 500px;height: 320px;background-image: url('bg.png');background-size: cover;z-index: -1;}.container {width: 600px;padding: 20px;background-color: rgba(255, 255, 255, 0.9); /* 半透明背景 */border-radius: 8px;box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);backdrop-filter: blur(10px); /* 毛玻璃特效 */display: flex;flex-direction: column;}.form-group {margin-bottom: 15px;display: flex;align-items: center;}.form-group label {flex: 1;margin-right: 10px;}.form-group input[type="text"],.form-group input[type="email"],.form-group input[type="password"],.form-group input[type="number"],.form-group textarea {flex: 2;padding: 8px;border: 1px solid #ddd;border-radius: 4px;}.form-group input[type="radio"],.form-group input[type="checkbox"] {margin-right: 5px;}.form-group textarea {resize: none;}.hobbies {display: flex;justify-content: space-between;}.register-btn {width: 100%;padding: 10px;background-color: blue;color: white;border: none;border-radius: 4px;cursor: pointer;}.register-btn:hover {background-color: darkblue;}</style>
</head>
<body><div class="background-image"></div><div class="container"><h2>用户注册</h2><form action="RegServlet" method="post"><div class="form-group"><label for="name">昵称:</label><input type="text" id="name" name="name" required></div><div class="form-group"><label for="email">注册邮箱:</label><input type="email" id="email" name="email" required></div><div class="form-group"><label for="password">密码:</label><input type="password" id="password" name="password" required></div><div class="form-group"><label>性别:</label><input type="radio" id="male" name="gender" value="male"><label for="male">男</label><input type="radio" id="female" name="gender" value="female"><label for="female">女</label></div><div class="form-group"><label for="age">年龄:</label><input type="number" id="age" name="age" required></div><div class="form-group"><label>兴趣爱好:</label><div class="hobbies"><input type="checkbox" id="hobby1" name="hobby" value="hobby1"><label for="hobby1">爱好1</label><input type="checkbox" id="hobby2" name="hobby" value="hobby2"><label for="hobby2">爱好2</label><input type="checkbox" id="hobby3" name="hobby" value="hobby3"><label for="hobby3">爱好3</label></div><div class="hobbies"><input type="checkbox" id="hobby4" name="hobby" value="hobby4"><label for="hobby4">爱好4</label><input type="checkbox" id="hobby5" name="hobby" value="hobby5"><label for="hobby5">爱好5</label><input type="checkbox" id="hobby6" name="hobby" value="hobby6"><label for="hobby6">爱好6</label></div></div><div class="form-group"><label for="introduction">自我介绍:</label><textarea id="introduction" name="introduction" maxlength="100" required></textarea></div><button type="submit" class="register-btn">立即注册</button></form></div>
</body>
</html>
- 登录页面: 创建
login.jsp
。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head><title>登录页面</title><style>body {font-family: Arial, sans-serif;background-color: #f7f7f7;padding: 20px;}.login-container {max-width: 300px;margin: 0 auto;background: #fff;padding: 20px;border-radius: 5px;box-shadow: 0 2px 4px rgba(0,0,0,0.1);}label {display: block;margin-bottom: 5px;}input[type="email"],input[type="password"] {width: 100%;padding: 10px;margin-bottom: 10px;border: 1px solid #ddd;border-radius: 4px;}button {width: 100%;padding: 10px;background-color: #5cb85c;color: white;border: none;border-radius: 4px;cursor: pointer;}button:hover {background-color: #4cae4c;}</style>
</head>
<body><div class="login-container"><h2>登录</h2><form action="LoginServlet" method="post"><div><label for="email">邮箱:</label><input type="email" id="email" name="email" required></div><div><label for="password">密码:</label><input type="password" id="password" name="password" required></div><button type="submit">登录</button></form></div>
</body>
</html>
- 修改密码页面: 创建
changePassword.jsp
。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head><title>修改密码</title><style>body {font-family: 'Arial', sans-serif;background-color: #f7f7f7;padding: 20px;}.form-container {max-width: 300px;margin: 0 auto;background: #fff;padding: 20px;border-radius: 5px;box-shadow: 0 2px 4px rgba(0,0,0,0.1);}label {display: block;margin-bottom: 5px;}input[type="text"],input[type="password"] {width: 100%;padding: 10px;margin-bottom: 10px;border: 1px solid #ddd;border-radius: 4px;}button {width: 100%;padding: 10px;background-color: #5cb85c;color: white;border: none;border-radius: 4px;cursor: pointer;}button:hover {background-color: #4cae4c;}.error-message {color: red;margin-bottom: 10px;}</style>
</head>
<body><div class="form-container"><h2>修改密码</h2><% if(request.getAttribute("error") != null) { %><div class="error-message"><%= request.getAttribute("error") %></div><% } %><form action="ChangePasswordServlet" method="post"><label for="email">邮箱:</label><input type="text" id="email" name="email" required><br><label for="oldPassword">旧密码:</label><input type="password" id="oldPassword" name="oldPassword" required><br><label for="newPassword">新密码:</label><input type="password" id="newPassword" name="newPassword" required><br><label for="confirmPassword">确认新密码:</label><input type="password" id="confirmPassword" name="confirmPassword" required><br><button type="submit">提交</button></form></div>
</body>
</html>
- 查询页面: 创建
Query.jsp
。
8 - 查询结果页面: 创建
QueryResult.jsp
。
步骤 6: 部署和测试
- 将项目部署到Tomcat服务器。
- 启动Tomcat服务器。
- 在浏览器中测试所有功能。
结论
通过本教程,您将学会如何使用Java Servlet和JSP构建一个完整的Web应用程序。这个项目涵盖了用户注册、登录、注销、修改密码和查询等基本功能,是学习Java Web开发的好起点。
附录
- 数据库配置: 数据库连接字符串和JDBC驱动。
- Servlet映射:
web.xml
中的Servlet配置。 - 错误处理: 如何在应用程序中处理和显示错误信息。