为什么会有免费制作网站,朋友圈网站文章怎么做,公司网站费怎么做分录,电子商务网站建设的方法有哪些简介
本教程将指导您如何使用Java Servlet和JSP技术构建一个简单的Web应用程序。该应用程序将包括用户注册、登录、注销#xff08;删除用户信息#xff09;、修改密码以及根据性别查询用户信息等功能。我们将使用MySQL数据库来存储用户数据。
环境准备
Java Development …简介
本教程将指导您如何使用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 importjava.sql.* %
% page contentTypetext/html;charsetUTF-8 languagejava %
html
headtitle创建表并插入数据/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?useSSLfalseserverTimezoneUTC, 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.doeexample.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?useSSLfalseserverTimezoneUTC;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?errorinvalidCredentials);}} catch (SQLException e) {e.printStackTrace();response.sendRedirect(login.jsp?errordatabaseError);} 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;charsetUTF-8);PrintWriter out response.getWriter();String sex request.getParameter(sex);System.out.print(查询性别: sex);ArrayListStudent 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 languagejava contentTypetext/html; charsetUTF-8 pageEncodingUTF-8%
!DOCTYPE html
html
headtitle用户注册页面/titlestylebody {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[typetext],.form-group input[typeemail],.form-group input[typepassword],.form-group input[typenumber],.form-group textarea {flex: 2;padding: 8px;border: 1px solid #ddd;border-radius: 4px;}.form-group input[typeradio],.form-group input[typecheckbox] {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
bodydiv classbackground-image/divdiv classcontainerh2用户注册/h2form actionRegServlet methodpostdiv classform-grouplabel forname昵称:/labelinput typetext idname namename required/divdiv classform-grouplabel foremail注册邮箱:/labelinput typeemail idemail nameemail required/divdiv classform-grouplabel forpassword密码:/labelinput typepassword idpassword namepassword required/divdiv classform-grouplabel性别:/labelinput typeradio idmale namegender valuemalelabel formale男/labelinput typeradio idfemale namegender valuefemalelabel forfemale女/label/divdiv classform-grouplabel forage年龄:/labelinput typenumber idage nameage required/divdiv classform-grouplabel兴趣爱好:/labeldiv classhobbiesinput typecheckbox idhobby1 namehobby valuehobby1label forhobby1爱好1/labelinput typecheckbox idhobby2 namehobby valuehobby2label forhobby2爱好2/labelinput typecheckbox idhobby3 namehobby valuehobby3label forhobby3爱好3/label/divdiv classhobbiesinput typecheckbox idhobby4 namehobby valuehobby4label forhobby4爱好4/labelinput typecheckbox idhobby5 namehobby valuehobby5label forhobby5爱好5/labelinput typecheckbox idhobby6 namehobby valuehobby6label forhobby6爱好6/label/div/divdiv classform-grouplabel forintroduction自我介绍:/labeltextarea idintroduction nameintroduction maxlength100 required/textarea/divbutton typesubmit classregister-btn立即注册/button/form/div
/body
/html登录页面: 创建 login.jsp。
% page languagejava contentTypetext/html; charsetUTF-8 pageEncodingUTF-8%
!DOCTYPE html
html
headtitle登录页面/titlestylebody {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[typeemail],input[typepassword] {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
bodydiv classlogin-containerh2登录/h2form actionLoginServlet methodpostdivlabel foremail邮箱:/labelinput typeemail idemail nameemail required/divdivlabel forpassword密码:/labelinput typepassword idpassword namepassword required/divbutton typesubmit登录/button/form/div
/body
/html修改密码页面: 创建 changePassword.jsp。
% page languagejava contentTypetext/html; charsetUTF-8 pageEncodingUTF-8%
!DOCTYPE html
html
headtitle修改密码/titlestylebody {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[typetext],input[typepassword] {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
bodydiv classform-containerh2修改密码/h2% if(request.getAttribute(error) ! null) { %div classerror-message% request.getAttribute(error) %/div% } %form actionChangePasswordServlet methodpostlabel foremail邮箱/labelinput typetext idemail nameemail requiredbrlabel foroldPassword旧密码/labelinput typepassword idoldPassword nameoldPassword requiredbrlabel fornewPassword新密码/labelinput typepassword idnewPassword namenewPassword requiredbrlabel forconfirmPassword确认新密码/labelinput typepassword idconfirmPassword nameconfirmPassword requiredbrbutton typesubmit提交/button/form/div
/body
/html查询页面: 创建 Query.jsp。 8查询结果页面: 创建 QueryResult.jsp。
步骤 6: 部署和测试
将项目部署到Tomcat服务器。启动Tomcat服务器。在浏览器中测试所有功能。
结论
通过本教程您将学会如何使用Java Servlet和JSP构建一个完整的Web应用程序。这个项目涵盖了用户注册、登录、注销、修改密码和查询等基本功能是学习Java Web开发的好起点。
附录
数据库配置: 数据库连接字符串和JDBC驱动。Servlet映射: web.xml 中的Servlet配置。错误处理: 如何在应用程序中处理和显示错误信息。