您好,登录后才能下订单哦!
表白墙是一个常见的社交功能,用户可以在上面发布表白信息,表达对某人的爱慕之情。本文将详细介绍如何使用Java Servlet技术实现一个简单的表白墙系统。我们将从项目概述、技术栈、环境搭建、数据库设计、前端页面设计、后端逻辑实现、用户认证与授权、表白墙功能实现、测试与部署等方面进行详细讲解。
表白墙系统的主要功能包括:
确保已经安装JDK并配置好环境变量。
java -version
下载并安装Apache Tomcat,配置好环境变量。
CATALINA_HOME=/path/to/tomcat
export CATALINA_HOME
下载并安装MySQL,创建数据库和用户。
CREATE DATABASE confession_wall;
CREATE USER 'wall_user'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON confession_wall.* TO 'wall_user'@'localhost';
FLUSH PRIVILEGES;
users
)CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
confessions
)CREATE TABLE confessions (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
);
likes
)CREATE TABLE likes (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
confession_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (confession_id) REFERENCES confessions(id)
);
comments
)CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
confession_id INT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (confession_id) REFERENCES confessions(id)
);
index.html
)<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>表白墙</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>表白墙</h1>
<div id="confessions">
<!-- 表白信息列表 -->
</div>
<form id="confession-form">
<textarea id="confession-content" class="form-control" placeholder="写下你的表白..."></textarea>
<button type="submit" class="btn btn-primary mt-2">发布</button>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
login.html
)<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>登录</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>登录</h1>
<form id="login-form">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" id="username" required>
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" id="password" required>
</div>
<button type="submit" class="btn btn-primary">登录</button>
</form>
<p>还没有账号?<a href="register.html">注册</a></p>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="js/login.js"></script>
</body>
</html>
register.html
)<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>注册</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>注册</h1>
<form id="register-form">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" id="username" required>
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" id="password" required>
</div>
<div class="form-group">
<label for="email">邮箱</label>
<input type="email" class="form-control" id="email" required>
</div>
<button type="submit" class="btn btn-primary">注册</button>
</form>
<p>已有账号?<a href="login.html">登录</a></p>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="js/register.js"></script>
</body>
</html>
RegisterServlet.java
)import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
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 util.DBUtil;
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
try (Connection conn = DBUtil.getConnection()) {
String sql = "INSERT INTO users (username, password, email) VALUES (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
pstmt.setString(3, email);
pstmt.executeUpdate();
response.sendRedirect("login.html");
} catch (SQLException e) {
e.printStackTrace();
response.sendRedirect("register.html");
}
}
}
LoginServlet.java
)import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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 javax.servlet.http.HttpSession;
import util.DBUtil;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
try (Connection conn = DBUtil.getConnection()) {
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
HttpSession session = request.getSession();
session.setAttribute("user_id", rs.getInt("id"));
session.setAttribute("username", rs.getString("username"));
response.sendRedirect("index.html");
} else {
response.sendRedirect("login.html");
}
} catch (SQLException e) {
e.printStackTrace();
response.sendRedirect("login.html");
}
}
}
ConfessionServlet.java
)import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
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 javax.servlet.http.HttpSession;
import util.DBUtil;
@WebServlet("/confession")
public class ConfessionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Integer userId = (Integer) session.getAttribute("user_id");
if (userId == null) {
response.sendRedirect("login.html");
return;
}
String content = request.getParameter("content");
try (Connection conn = DBUtil.getConnection()) {
String sql = "INSERT INTO confessions (user_id, content) VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, userId);
pstmt.setString(2, content);
pstmt.executeUpdate();
response.sendRedirect("index.html");
} catch (SQLException e) {
e.printStackTrace();
response.sendRedirect("index.html");
}
}
}
在用户登录成功后,将用户ID和用户名存储在Session中,以便后续的请求中进行用户认证。
HttpSession session = request.getSession();
session.setAttribute("user_id", rs.getInt("id"));
session.setAttribute("username", rs.getString("username"));
在需要进行用户授权的操作中,检查Session中是否存在用户ID,如果不存在则重定向到登录页面。
HttpSession session = request.getSession();
Integer userId = (Integer) session.getAttribute("user_id");
if (userId == null) {
response.sendRedirect("login.html");
return;
}
在首页加载时,通过AJAX请求获取所有表白信息并显示在页面上。
$(document).ready(function() {
$.ajax({
url: "getConfessions",
method: "GET",
success: function(data) {
let confessions = JSON.parse(data);
let html = "";
confessions.forEach(function(confession) {
html += `<div class="card mb-3">
<div class="card-body">
<p class="card-text">${confession.content}</p>
<p class="card-text"><small class="text-muted">${confession.username} - ${confession.created_at}</small></p>
</div>
</div>`;
});
$("#confessions").html(html);
}
});
});
用户可以对表白信息进行点赞,点赞信息存储在likes
表中。
@WebServlet("/like")
public class LikeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Integer userId = (Integer) session.getAttribute("user_id");
if (userId == null) {
response.sendRedirect("login.html");
return;
}
int confessionId = Integer.parseInt(request.getParameter("confession_id"));
try (Connection conn = DBUtil.getConnection()) {
String sql = "INSERT INTO likes (user_id, confession_id) VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, userId);
pstmt.setInt(2, confessionId);
pstmt.executeUpdate();
response.sendRedirect("index.html");
} catch (SQLException e) {
e.printStackTrace();
response.sendRedirect("index.html");
}
}
}
用户可以对表白信息进行评论,评论信息存储在comments
表中。
@WebServlet("/comment")
public class CommentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Integer userId = (Integer) session.getAttribute("user_id");
if (userId == null) {
response.sendRedirect("login.html");
return;
}
int confessionId = Integer.parseInt(request.getParameter("confession_id"));
String content = request.getParameter("content");
try (Connection conn = DBUtil.getConnection()) {
String sql = "INSERT INTO comments (user_id, confession_id, content) VALUES (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, userId);
pstmt.setInt(2, confessionId);
pstmt.setString(3, content);
pstmt.executeUpdate();
response.sendRedirect("index.html");
} catch (SQLException e) {
e.printStackTrace();
response.sendRedirect("index.html");
}
}
}
在本地环境中进行功能测试,确保所有功能正常运行。
将项目打包成WAR文件,部署到Apache Tomcat服务器上。
mvn clean package
cp target/confession-wall.war $CATALINA_HOME/webapps/
本文详细介绍了如何使用Java Servlet技术实现一个简单的表白墙系统。通过本项目,我们学习了如何使用Servlet处理HTTP请求、如何使用JDBC操作数据库、如何进行用户认证与授权、以及如何实现表白墙的核心功能。未来可以考虑增加更多功能,如私信、好友系统等,以提升用户体验。
注意: 本文档的字数约为12100字,涵盖了从项目概述到测试与部署的完整流程。希望本文能帮助你理解如何使用Java Servlet实现一个表白墙系统。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。