简介
本教程将指导您如何使用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