• 前端+后端项目 - 论坛信息管理系统(Web+servlet+MySQL+JDBC)


    🤞目录🤞

    💖一. 准备工作

    💎1) 创建 web 项目

    💎2) 创建目录结构

    💎3) 配置 pom.xml

    💖二. 数据库操作代码

    💎1. 数据库设计

    1.1 ER图

    1.2 ER图转化为关系模型并优化

    1.3 创建数据库/表结构

    💎2. 封装数据库

    1.  DBUtil 类(JDBC连接数据库)

    2. 创建实体类

            2.1 User

            2.2 Section

            2.3 Topic

            2.4 Reply

            2.5 Key

    3. 封装对数据库的增删查改类

            3.1 UserDao

            3.2 SectionDao

            3.3 TopicDao

            3.4 ReplyDao

            3.5 KeyDao

    💖三. 约定前后端交互接口

    💎0. 前端页面

    💎1. 实现论坛列表页

    1.1约定前后端交互接口

    1.2 实现服务器代码

    1.3 编写客户端代码

    💎2. 实现论坛主贴页

    2.1约定前后端交互接口

    2.2 实现服务器代码

    2.3 编写客户端代码

    💎3. 实现论坛回复页

    3.1约定前后端交互接口

    3.2 实现服务器代码

    3.3 编写客户端代码

    💎4. 实现论坛个人中心页

    4.1约定前后端交互接口

    4.2 实现服务器代码

    4.3 编写客户端代码

    💎5. 实现论坛发布帖子页

    5.1约定前后端交互接口

    5.2 实现服务器代码

     5.3 编写客户端代码

    💎6. 实现论坛登录页

    6.1约定前后端交互接口

    6.2 实现服务器代码

    6.3 编写客户端代码

    💎7. 实现论坛注册页

    7.1约定前后端交互接口

    7.2 实现服务器代码

    7.3 编写客户端代码

    💎8. 实现论坛注销

    8.1实现服务器代码


    【大家好,我是爱干饭的猿,如果喜欢这篇文章,点个赞👍,关注一下吧,后续会持续分享其他项目的相关操作和Linux相关知识

    上一篇文章:《前端项目 - 论坛信息管理系统(纯页面)》

    本篇文章介绍的《论坛信息管理系统》源码链接放在文章末尾了,感兴趣的朋友可以看看。


    上一篇文章中我们完成了论坛信息管理系统的前端页面,现在我们可以基于模板的方式,通过服务器把数据渲染到页面中,然后直接返回完整的页面给浏览器。

    目前比较主流的开发方式是“前后端分离”的方式,在这种方式下服务端不关注页面的内容,而是网页提供的数据。

    网页可以通过ajax的方式和服务器之间交互数据,网页拿到数据之后再根据数据的内容渲染到页面上。

    此篇文章仅展示重要代码思路过程,项目源码在 gitee 中

    效果展示

    论坛列表页:

    论坛主贴页:

    论坛回帖页:

    用户写帖子页:

    用户个人信息页:

    论坛登录页:

     论坛注册页:


     

    一. 准备工作

    1) 创建 web 项目

    2) 创建目录结构

    3) 配置 pom.xml

    1. <project xmlns="http://maven.apache.org/POM/4.0.0"
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0modelVersion>
    5. <groupId>org.examplegroupId>
    6. <artifactId>forum-inforation-management-systemartifactId>
    7. <version>1.0-SNAPSHOTversion>
    8. <packaging>warpackaging>
    9. <properties>
    10. <maven.compiler.source>1.8maven.compiler.source>
    11. <maven.compiler.target>1.8maven.compiler.target>
    12. properties>
    13. <dependencies>
    14. <dependency>
    15. <groupId>javax.servletgroupId>
    16. <artifactId>javax.servlet-apiartifactId>
    17. <version>3.1.0version>
    18. <scope>providedscope>
    19. dependency>
    20. <dependency>
    21. <groupId>mysqlgroupId>
    22. <artifactId>mysql-connector-javaartifactId>
    23. <version>5.1.49version>
    24. dependency>
    25. <dependency>
    26. <groupId>com.fasterxml.jackson.coregroupId>
    27. <artifactId>jackson-databindartifactId>
    28. <version>2.12.4version>
    29. dependency>
    30. <dependency>
    31. <groupId>org.projectlombokgroupId>
    32. <artifactId>lombokartifactId>
    33. <version>1.18.20version>
    34. <scope>compilescope>
    35. dependency>
    36. dependencies>
    37. project>

    二. 数据库操作代码

    1. 数据库设计

    1.1 ER图

    1.2 ER图转化为关系模型并优化

    1. 管理员信息表管理员编号,管理员名称,管理员密码
    2. 用户信息表用户编号,用户名称,用户密码,用户生日,用户性别,用户性别,用户生日,用户职业,用户爱好,用户帖子数,用户等级,用户注册日期
    3. 块信息表版块编号,版主编号,版块名称,版块说明,版块点击次数,版块主题数
    4. 主贴信息表主贴编号主贴板块编号主贴用户编号主贴回复次数主贴标题主贴内容主贴时间主贴回复次数,主贴点击次数
    5. 回复贴信息表回帖编号回帖主题帖子编号回帖的用户编号回帖标题回帖内容回帖时间回帖点击次数

    1.3 创建数据库/表结构

    根据在ER图中的实体,创建库表结构
    db.sql
    1. -- 创建数据库
    2. if exit forum_management_information_system1 drop database `forum_management_information_system1`;
    3. CREATE SCHEMA `forum_management_information_system1` DEFAULT CHARACTER SET utf8 ;
    4. -- 创建管理员信息表
    5. CREATE TABLE `admin` (
    6. `adminID` int NOT NULL AUTO_INCREMENT COMMENT '管理员编号',
    7. `adminName` varchar(20) NOT NULL COMMENT '管理员名称',
    8. `adminPassword` varchar(20) NOT NULL COMMENT '管理员密码',
    9. PRIMARY KEY (`adminID`)
    10. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COMMENT='管理员信息表';
    11. -- 创建用户信息表
    12. CREATE TABLE `user` (
    13. `uID` int NOT NULL AUTO_INCREMENT COMMENT '用户编号',
    14. `userName` varchar(20) NOT NULL COMMENT '用户昵称',
    15. `userPassword` varchar(20) NOT NULL COMMENT '用户密码',
    16. `userSex` varchar(20) NOT NULL COMMENT '用户性别',
    17. `userAge` int NOT NULL COMMENT '用户生日',
    18. `userOccupation` varchar(20) NOT NULL COMMENT '用户职业',
    19. `userHobby` varchar(20) NOT NULL COMMENT '用户爱好',
    20. `userPoint` int NOT NULL DEFAULT '0' COMMENT '用户积分',
    21. `userClass` int NOT NULL DEFAULT '0' COMMENT '用户等级',
    22. `userRegister` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '用户注册时间',
    23. PRIMARY KEY (`uID`)
    24. ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb3 COMMENT='用户信息表';
    25. -- 板块信息表
    26. CREATE TABLE `section` (
    27. `sID` int NOT NULL AUTO_INCREMENT COMMENT '板块编号',
    28. `uID` int NOT NULL COMMENT '版主编号(用户编号)',
    29. `sName` varchar(50) NOT NULL COMMENT '板块名称',
    30. `sStatement` text NOT NULL COMMENT '板块说明',
    31. `sClickCount` int NOT NULL DEFAULT '0' COMMENT '板块点击次数',
    32. `sTopicCount` int NOT NULL DEFAULT '0' COMMENT '板块主题数',
    33. PRIMARY KEY (`sID`),
    34. KEY `s_uID_idx` (`uID`)
    35. ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb3 COMMENT='板块信息表';
    36. -- 主贴信息表
    37. CREATE TABLE `topic` (
    38. `tID` int NOT NULL AUTO_INCREMENT COMMENT '主贴编号',
    39. `sID` int NOT NULL COMMENT '主贴板块编号',
    40. `uID` int NOT NULL COMMENT '主贴用户编号',
    41. `tTopic` varchar(20) NOT NULL COMMENT '主贴标题',
    42. `tContent` text NOT NULL COMMENT '主贴内容',
    43. `tTime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '主贴时间',
    44. `tReplyCount` int NOT NULL DEFAULT '0' COMMENT '主贴回复次数',
    45. `tClickCount` int NOT NULL DEFAULT '0' COMMENT '主贴点击次数',
    46. PRIMARY KEY (`tID`),
    47. KEY `t_uID_idx` (`uID`),
    48. KEY `t_sID_idx` (`sID`),
    49. CONSTRAINT `t_sID` FOREIGN KEY (`sID`) REFERENCES `section` (`sID`),
    50. CONSTRAINT `t_uID` FOREIGN KEY (`uID`) REFERENCES `user` (`uID`)
    51. ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb3 COMMENT='主贴信息表';
    52. -- 回复贴信息表
    53. CREATE TABLE `reply` (
    54. `rID` int NOT NULL AUTO_INCREMENT COMMENT '回帖编号',
    55. `tID` int NOT NULL COMMENT '回帖主题帖子编号(主贴信息表)',
    56. `uID` int NOT NULL COMMENT '回帖的用户编号',
    57. `rTopic` varchar(20) NOT NULL DEFAULT '回帖' COMMENT '回帖标题',
    58. `rContent` text NOT NULL COMMENT '回帖内容',
    59. `rTime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '回帖时间',
    60. `rClickCount` int NOT NULL DEFAULT '0' COMMENT '回帖点击次数',
    61. PRIMARY KEY (`rID`)
    62. ) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8mb3 COMMENT='回复贴信息表';
    63. -- 初始数据 (增加一个用户)
    64. INSERT INTO `forum_management_information_system1`.`user` (`userName`, `userPassword`, `userSex`, `userAge`, `userOccupation`, `userHobby`) VALUES ('管理员', '123456', '男', '18', '管理员', '你猜');
    65. -- 初始化板块数据
    66. INSERT INTO `forum_management_information_system1`.`section` (`uID`, `sName`, `sStatement`) VALUES ('1', '网易云', '小时候枕头上全是口水,长大后枕头上全是泪水;小时候微笑是一个心情,长大后微笑是一种表情;小时候哭着哭着就笑了,长大后笑着笑着就哭了。我们终于到了小时候最羡慕的年龄,但却没有成为小时候最想成为的人。——网易云音乐热评《当我已不再那么年轻》');
    67. INSERT INTO `forum_management_information_system1`.`section` (`uID`, `sName`, `sStatement`) VALUES ('1', '码农', '码农Coding Peasant(s):可以指在程序设计某个专业领域中的专业人士,或是从事软体撰写,程序开发、维护的专业人员。但一般Coder特指进行编写代码的编码员。');
    68. INSERT INTO `forum_management_information_system1`.`section` (`uID`, `sName`, `sStatement`) VALUES ('1', '电影', '电影,也被称为运动画面或动态画面,即“映画”,是作品视觉艺术形式,通过使用移动图像来表达沟通思想,故事,认知,情感,价值观,或各类大气模拟体验。这些图像通常伴随着声音,很少有其他感官刺激。 “电影”一词是电影摄影的缩写,通常用于指代电影制作和电影业,以及由此产生的艺术形式。');
    69. INSERT INTO `forum_management_information_system1`.`section` (`uID`, `sName`, `sStatement`) VALUES ('1', '体育', '( physical education ,缩写 PE 或 P.E. ),是一种复杂的社会文化现象,它是一种以身体与智力活动为基本手段,根据人体生长发育、技能形成和机能提高等规律,达到促进全面发育、提高身体素质与全面教育水平、增强体质与提高运动能力、改善生活方式与提高生活质量的一种有意识、有目的、有组织的社会活动。');
    70. INSERT INTO `forum_management_information_system1`.`section` (`uID`, `sName`, `sStatement`) VALUES ('1', '游戏', '游戏(英文: Game)是所有哺乳类动物,特别是灵长类动物学习生存的第一步。它是一种基于物质需求满足之上的,在一些特定时间、空间范围内遵循某种特定规则的,追求精神世界需求满足的社会行为方式,但同时这种行为方式也是哺乳类动物或者灵长类动物所需的一种降压减排的方式,不管是在出生幼年期,或者发育期,成熟期都会需要的一种行为方式。');
    71. INSERT INTO `forum_management_information_system1`.`section` (`uID`, `sName`, `sStatement`) VALUES ('1', '旅行', '“旅”是旅行,外出,即为了实现某一目的而在空间上从甲地到乙地的行进过程;“游”是外出游览、观光、娱乐,即为达到这些目的所作的旅行。二者合起来即旅游。所以,旅行偏重于行,旅游不但有“行”,且有观光、娱乐含义。');
    72. INSERT INTO `forum_management_information_system1`.`section` (`uID`, `sName`, `sStatement`) VALUES ('1', '明星', ' (拼音míng xīng,注音ㄇㄧㄥˊ ㄒㄧㄥ)汉语 词语 ,古书上指金星;旧时指 交际 场中有名的女子;现指在某个领域内有一定影响力的人物。 泛指有名的 演员 、 歌手 、 艺人 、 运动员 等。');

    2. 封装数据库

     1.  DBUtil 类(JDBC连接数据库)

    1. package forum.util;
    2. import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
    3. import lombok.SneakyThrows;
    4. import javax.sql.DataSource;
    5. import java.sql.Connection;
    6. /**
    7. * @author haomin
    8. * @date 2022/06/29 17:23
    9. **/
    10. public class DBUtil {
    11. private static final DataSource dataSource;
    12. static {
    13. MysqlDataSource mysqlDataSource = new MysqlDataSource();
    14. // 数据库路径要正确
    15. mysqlDataSource.setUrl("jdbc:mysql:///forum_management_information_system1?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai");
    16. mysqlDataSource.setUser("root");
    17. mysqlDataSource.setPassword("123456");
    18. dataSource = mysqlDataSource;
    19. }
    20. @SneakyThrows
    21. public static Connection connection() {
    22. return dataSource.getConnection();
    23. }
    24. }

    2. 创建实体类

    一般放对象的目录命名为model,根据model目录,其中存放的都是各种对象,例如  User 类、Topic 类、Reply 类。
    使用@Data注解在类上时,不用再手动添加get/set等方法了,简化代码

    2.1 User

    1. package forum.model;
    2. import lombok.Data;
    3. // 使用@Data注解在类上时,不用再手动添加get/set等方法了,简化代码
    4. @Data
    5. public class User {
    6. public Integer uID;
    7. public String username;
    8. public String password;
    9. public String userSex;
    10. public Integer userAge;
    11. public String userOccupation;
    12. public String userHobby;
    13. public Integer userPoint;
    14. public Integer userClass;
    15. public String userRegister;
    16. }

    2.2 Section

    1. package forum.model;
    2. import lombok.Data;
    3. @Data
    4. public class Section {
    5. public Integer sID;
    6. public Integer uID;
    7. public String sName;
    8. public String sStatement;
    9. public Integer sClickCount;
    10. public Integer sTopicCount;
    11. }

    2.3 Topic

    1. package forum.model;
    2. import com.fasterxml.jackson.annotation.JsonFormat;
    3. import lombok.Data;
    4. import java.util.Date;
    5. @Data
    6. public class Topic {
    7. public Integer tID;
    8. public Integer sID;
    9. public Integer uID;
    10. public String username;
    11. public String tTopic;
    12. public String tContent;
    13. //@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    14. public String tTime;
    15. public Integer tReplyCount;
    16. public Integer tClickCount;
    17. }

    2.4 Reply

    1. package forum.model;
    2. import com.fasterxml.jackson.annotation.JsonFormat;
    3. import java.util.Date;
    4. public class Reply {
    5. public Integer rID;
    6. public Integer tID;
    7. public Integer uID;
    8. public String username;
    9. public String rTopic;
    10. public String rContent;
    11. public String rTime;
    12. public Integer rClickCount;
    13. }

    2.5 Key

    为实现一个搜索功能,新建了一个Keyword实体

    1. package forum.model;
    2. import lombok.Data;
    3. @Data
    4. public class Keyword {
    5. public String keyword;
    6. }

    3. 封装对数据库的增删查改类

    一般放数据库增删查改的目录命名为dao,根据dao目录,其中存放的都是各种数据库增删查改方法类,例如 UserDao 类 , SectionDao 类。

    3.1 UserDao

    1. package forum.dao;
    2. import forum.model.User;
    3. import forum.util.DBUtil;
    4. import lombok.SneakyThrows;
    5. import java.sql.Connection;
    6. import java.sql.PreparedStatement;
    7. import java.sql.ResultSet;
    8. /**
    9. * @author haomin
    10. * @date 2022/06/29 17:22
    11. **/
    12. // 从数据库查找user数据的方法类
    13. public class UserDao {
    14. // 用户帖子数
    15. @SneakyThrows
    16. public int selectPointCountByUid(int uid){
    17. String sql = "select count(*) from topic where uID = ?";
    18. try (Connection c = DBUtil.connection()){
    19. try (PreparedStatement ps = c.prepareStatement(sql)){
    20. ps.setInt(1,uid);
    21. try (ResultSet rs = ps.executeQuery()){
    22. rs.next();
    23. int count = rs.getInt("count(*)");
    24. updatePointCountByUid(uid,count);
    25. return count;
    26. }
    27. }
    28. }
    29. }
    30. // 更新主贴回复数
    31. @SneakyThrows
    32. public void updatePointCountByUid(int uID, int count) {
    33. String sql = "update user set userPoint = ? where uID = ?";
    34. try (Connection c = DBUtil.connection()) {
    35. try (PreparedStatement ps = c.prepareStatement(sql)) {
    36. ps.setInt(1,count);
    37. ps.setInt(2,uID);
    38. ps.executeUpdate();
    39. }
    40. }
    41. }
    42. // 用户等级
    43. public int selectClassCountByUid(int uid){
    44. int point = new UserDao().selectPointCountByUid(uid);
    45. int classCount = 0;
    46. if(point == 0){
    47. classCount = 0;
    48. }else if(point < 5){
    49. classCount = 1;
    50. }else if(point < 15){
    51. classCount = 2;
    52. }else if(point < 30){
    53. classCount = 3;
    54. }else {
    55. classCount = 4;
    56. }
    57. updateClassCountByUid(uid,classCount);
    58. return classCount;
    59. }
    60. @SneakyThrows
    61. private void updateClassCountByUid(int uID, int classCount) {
    62. String sql = "update user set userClass = ? where uID = ?";
    63. try (Connection c = DBUtil.connection()) {
    64. try (PreparedStatement ps = c.prepareStatement(sql)) {
    65. ps.setInt(1,classCount);
    66. ps.setInt(2,uID);
    67. ps.executeUpdate();
    68. }
    69. }
    70. }
    71. // 查询用户ByUsernameAndPassword
    72. @SneakyThrows
    73. public User selectOneByUsernameAndPassword(String username,String password){
    74. String sql = "select uID, userSex, userAge,userOccupation, userHobby, userPoint, userClass, userRegister from user where userName = ? and userPassword = ?";
    75. try (Connection c = DBUtil.connection()){
    76. try (PreparedStatement ps = c.prepareStatement(sql)){
    77. ps.setString(1,username);
    78. ps.setString(2,password);
    79. System.out.println("DEBUG: " + ps);
    80. try (ResultSet rs = ps.executeQuery()){
    81. if(!rs.next()){
    82. return null;
    83. }
    84. User user = new User();
    85. user.uID = rs.getInt("uID");
    86. user.username = username;
    87. user.password = password;
    88. user.userSex = rs.getString("userSex");
    89. user.userAge = rs.getInt("userAge");
    90. user.userOccupation = rs.getString("userOccupation");
    91. user.userHobby = rs.getString("userHobby");
    92. user.userPoint = rs.getInt("userPoint");
    93. user.userClass = rs.getInt("userClass");
    94. String Time = rs.getString("userRegister");
    95. user.userRegister = Time.substring(0,Time.length()-5);
    96. return user;
    97. }
    98. }
    99. }
    100. }
    101. // 查询用户名ByUid
    102. @SneakyThrows
    103. public String selectUserNameByUid(int uid){
    104. String sql = "select username from user where uID = ?";
    105. try (Connection c = DBUtil.connection()){
    106. try (PreparedStatement ps = c.prepareStatement(sql)){
    107. ps.setInt(1,uid);
    108. try (ResultSet rs = ps.executeQuery()){
    109. if(!rs.next()){
    110. return null;
    111. }
    112. String username = rs.getString("username");
    113. return username;
    114. }
    115. }
    116. }
    117. }
    118. // 新建用户
    119. @SneakyThrows
    120. public User insert(String username, String password, String sex, int age, String occupation, String hobby) {
    121. String sql = "insert into user (username,userPassword,userSex,userAge,userOccupation,userHobby) values (?, ?, ?, ?, ?, ?)";
    122. try (Connection c = DBUtil.connection()){
    123. try (PreparedStatement ps = c.prepareStatement(sql)){
    124. ps.setString(1,username);
    125. ps.setString(2,password);
    126. ps.setString(3,sex);
    127. ps.setInt(4,age);
    128. ps.setString(5,occupation);
    129. ps.setString(6,hobby);
    130. ps.executeUpdate();
    131. System.out.println("新建用户完成");
    132. return new UserDao().selectOneByUsernameAndPassword(username,password);
    133. }
    134. }
    135. }
    136. }

    3.2 SectionDao

    1. package forum.dao;
    2. import forum.model.Section;
    3. import forum.util.DBUtil;
    4. import lombok.SneakyThrows;
    5. import java.sql.Connection;
    6. import java.sql.PreparedStatement;
    7. import java.sql.ResultSet;
    8. import java.util.ArrayList;
    9. import java.util.List;
    10. /**
    11. * @author haomin
    12. * @date 2022/06/30 11:32
    13. **/
    14. public class SectionDao {
    15. // 得到板块集合ByUid
    16. @SneakyThrows
    17. public List
      selectListByUid(){
    18. List
      list = new ArrayList<>();
    19. String sql = "select sID, uID, sName, sStatement, sClickCount, sTopicCount from section;";
    20. try (Connection c = DBUtil.connection()) {
    21. try (PreparedStatement ps = c.prepareStatement(sql)){
    22. System.out.println("DEBUG: " + ps);
    23. try (ResultSet rs = ps.executeQuery()){
    24. while (rs.next()){
    25. Section section = new Section();
    26. section.sID = rs.getInt("sID");
    27. section.uID = rs.getInt("uID");
    28. section.sName = rs.getString("sName");
    29. section.sStatement = rs.getString("sStatement");
    30. section.sClickCount = rs.getInt("sClickCount");
    31. section.sTopicCount = new TopicDao().sTopicCount(section.sID);
    32. list.add(section);
    33. }
    34. }
    35. }
    36. }
    37. return list;
    38. }
    39. // 得到板块集合ByKeyWord
    40. @SneakyThrows
    41. public List
      selectSectionListByKeyword(String keyword) {
    42. List
      list = new ArrayList<>();
    43. String sql = "select * from section where sName like ?;";
    44. System.out.println(sql);
    45. try (Connection c = DBUtil.connection()) {
    46. System.out.println(sql);
    47. try (PreparedStatement ps = c.prepareStatement(sql)){
    48. System.out.println(sql);
    49. String key = "%"+keyword+"%";
    50. ps.setString(1,key);
    51. System.out.println(sql);
    52. try (ResultSet rs = ps.executeQuery()){
    53. while (rs.next()){
    54. Section section = new Section();
    55. section.sID = rs.getInt("sID");
    56. section.uID = rs.getInt("uID");
    57. section.sName = rs.getString("sName");
    58. section.sStatement = rs.getString("sStatement");
    59. section.sClickCount = rs.getInt("sClickCount");
    60. section.sTopicCount = new TopicDao().sTopicCount(section.sID);
    61. list.add(section);
    62. }
    63. }
    64. }
    65. }
    66. return list;
    67. }
    68. // 更新浏览次数
    69. @SneakyThrows
    70. public void update(int sid) {
    71. String sql = "update section set sClickCount = sClickCount+1 where sid = ?";
    72. try (Connection c = DBUtil.connection()) {
    73. try (PreparedStatement ps = c.prepareStatement(sql)) {
    74. ps.setInt(1,sid);
    75. ps.executeUpdate();
    76. }
    77. }
    78. }
    79. }

    3.3 TopicDao

    1. package forum.dao;
    2. import forum.model.Section;
    3. import forum.model.Topic;
    4. import forum.model.User;
    5. import forum.util.DBUtil;
    6. import lombok.SneakyThrows;
    7. import java.sql.Connection;
    8. import java.sql.PreparedStatement;
    9. import java.sql.ResultSet;
    10. import java.util.ArrayList;
    11. import java.util.List;
    12. /**
    13. * @author haomin
    14. * @date 2022/06/30 16:38
    15. **/
    16. public class TopicDao {
    17. // 查询板块帖子数
    18. @SneakyThrows
    19. public int sTopicCount(Integer sID) {
    20. String sql = "select count(*) from topic where sID = ?";
    21. try (Connection c = DBUtil.connection()){
    22. try (PreparedStatement ps = c.prepareStatement(sql)){
    23. ps.setInt(1,sID);
    24. try (ResultSet rs = ps.executeQuery()){
    25. rs.next();
    26. int count = rs.getInt("count(*)");
    27. updateSTopicCount(sID, count);
    28. return count;
    29. }
    30. }
    31. }
    32. }
    33. // 更新板块帖子数
    34. @SneakyThrows
    35. public void updateSTopicCount(int sID, int count) {
    36. String sql = "update section set sTopicCount = ? where sID = ?";
    37. try (Connection c = DBUtil.connection()) {
    38. try (PreparedStatement ps = c.prepareStatement(sql)) {
    39. ps.setInt(1,count);
    40. ps.setInt(2,sID);
    41. ps.executeUpdate();
    42. }
    43. }
    44. }
    45. // 得到主贴集合BySid
    46. @SneakyThrows
    47. public List selectListByUid(int sid){
    48. List list = new ArrayList<>();
    49. String sql = "select tID, uID, tTopic, tContent, tTime, tReplyCount, tClickCount from topic where sID = ? order by tTime desc";
    50. try(Connection c = DBUtil.connection()){
    51. try (PreparedStatement ps = c.prepareStatement(sql)){
    52. ps.setInt(1,sid);
    53. System.out.println("DEBUG: " + ps);
    54. try (ResultSet rs = ps.executeQuery()){
    55. while (rs.next()){
    56. Topic topic = new Topic();
    57. topic.tID = rs.getInt("tID");
    58. topic.sID = sid;
    59. topic.uID = rs.getInt("uID");
    60. topic.username = new UserDao().selectUserNameByUid(topic.uID);
    61. topic.tTopic = rs.getString("tTopic");
    62. topic.tContent = rs.getString("tContent");
    63. String Time = rs.getString("tTime");
    64. topic.tTime = Time.substring(0,Time.length()-5);
    65. topic.tReplyCount = new ReplyDao().tReplyCount(topic.tID);
    66. topic.tClickCount = rs.getInt("tClickCount");
    67. list.add(topic);
    68. }
    69. }
    70. }
    71. }
    72. return list;
    73. }
    74. // 得到主贴集合ByKeyword
    75. @SneakyThrows
    76. public List selectTopicListByKeyword(String keyword) {
    77. List list = new ArrayList<>();
    78. String sql = "select * from topic where tTopic like ?;";
    79. System.out.println(sql);
    80. try (Connection c = DBUtil.connection()) {
    81. System.out.println(sql);
    82. try (PreparedStatement ps = c.prepareStatement(sql)){
    83. System.out.println(sql);
    84. String key = "%"+keyword+"%";
    85. ps.setString(1,key);
    86. System.out.println(sql);
    87. try (ResultSet rs = ps.executeQuery()){
    88. while (rs.next()){
    89. Topic topic = new Topic();
    90. topic.tID = rs.getInt("tID");
    91. topic.sID = rs.getInt("sId");
    92. topic.uID = rs.getInt("uID");
    93. topic.username = new UserDao().selectUserNameByUid(topic.uID);
    94. topic.tTopic = rs.getString("tTopic");
    95. topic.tContent = rs.getString("tContent");
    96. String Time = rs.getString("tTime");
    97. topic.tTime = Time.substring(0,Time.length()-5);
    98. topic.tReplyCount = new ReplyDao().tReplyCount(topic.tID);
    99. topic.tClickCount = rs.getInt("tClickCount");
    100. list.add(topic);
    101. }
    102. }
    103. }
    104. }
    105. return list;
    106. }
    107. // 查询一个主贴ByTid
    108. @SneakyThrows
    109. public Topic selectTopicByTid(int tid) {
    110. String sql = "select sID, uID, tTopic, tContent, tTime, tReplyCount, tClickCount from topic where tID = ?";
    111. try(Connection c = DBUtil.connection()){
    112. try (PreparedStatement ps = c.prepareStatement(sql)){
    113. ps.setInt(1,tid);
    114. System.out.println("DEBUG: " + ps);
    115. try (ResultSet rs = ps.executeQuery()){
    116. rs.next();
    117. Topic topic = new Topic();
    118. topic.tID = tid;
    119. topic.sID = rs.getInt("sID");
    120. topic.uID = rs.getInt("uID");
    121. topic.username = new UserDao().selectUserNameByUid(topic.uID);
    122. topic.tTopic = rs.getString("tTopic");
    123. topic.tContent = rs.getString("tContent");
    124. String Time = rs.getString("tTime");
    125. topic.tTime = Time.substring(0,Time.length()-5);
    126. topic.tReplyCount = new ReplyDao().tReplyCount(topic.tID);
    127. topic.tClickCount = rs.getInt("tClickCount");
    128. return topic;
    129. }
    130. }
    131. }
    132. }
    133. // 插入主贴
    134. @SneakyThrows
    135. public void insert(int sid, Integer uID, String title, String content) {
    136. String sql = "insert into topic (sID, uID, tTopic, tContent) values (?, ?, ?, ?)";
    137. try (Connection c = DBUtil.connection()){
    138. try (PreparedStatement ps = c.prepareStatement(sql)){
    139. ps.setInt(1,sid);
    140. ps.setInt(2,uID);
    141. ps.setString(3,title);
    142. ps.setString(4,content);
    143. ps.executeUpdate();
    144. System.out.println("插入完成");
    145. }
    146. }
    147. }
    148. // 更新主贴浏览次数
    149. @SneakyThrows
    150. public void update(int tid) {
    151. String sql = "update topic set tClickCount = tClickCount+1 where tid = ?";
    152. try (Connection c = DBUtil.connection()) {
    153. try (PreparedStatement ps = c.prepareStatement(sql)) {
    154. ps.setInt(1,tid);
    155. ps.executeUpdate();
    156. }
    157. }
    158. }
    159. }

    3.4 ReplyDao

    1. package forum.dao;
    2. import forum.model.Reply;
    3. import forum.util.DBUtil;
    4. import lombok.SneakyThrows;
    5. import java.sql.Connection;
    6. import java.sql.PreparedStatement;
    7. import java.sql.ResultSet;
    8. import java.util.ArrayList;
    9. import java.util.List;
    10. /**
    11. * @author haomin
    12. * @date 2022/06/30 16:38
    13. **/
    14. public class ReplyDao {
    15. // 查询主贴回复数
    16. @SneakyThrows
    17. public int tReplyCount(int tid){
    18. try (Connection c = DBUtil.connection()){
    19. String sql = "select count(*) from reply where tID = ?;";
    20. try (PreparedStatement ps = c.prepareStatement(sql)){
    21. ps.setInt(1,tid);
    22. try (ResultSet rs = ps.executeQuery()){
    23. rs.next();
    24. int count = rs.getInt("count(*)");
    25. updateTReplyCount(tid,count);
    26. return count;
    27. }
    28. }
    29. }
    30. }
    31. // 更新主贴回复数
    32. @SneakyThrows
    33. public void updateTReplyCount(int tID, int count) {
    34. String sql = "update topic set tReplyCount = ? where tID = ?";
    35. try (Connection c = DBUtil.connection()) {
    36. try (PreparedStatement ps = c.prepareStatement(sql)) {
    37. ps.setInt(1,count);
    38. ps.setInt(2,tID);
    39. ps.executeUpdate();
    40. }
    41. }
    42. }
    43. // 根据tid查询所有回复
    44. @SneakyThrows
    45. public List selectListByTid(int tid){
    46. List list = new ArrayList<>();
    47. String sql = "select rID, uID, rTopic, rContent, rTime, rClickCount from reply where tid = ? order by rTime desc";
    48. try (Connection c = DBUtil.connection()){
    49. try (PreparedStatement ps = c.prepareStatement(sql)){
    50. ps.setInt(1,tid);
    51. System.out.println("DEBUG: " + ps);
    52. try (ResultSet rs = ps.executeQuery()){
    53. while (rs.next()){
    54. Reply reply = new Reply();
    55. reply.rID = rs.getInt("rID");
    56. reply.tID = tid;
    57. reply.uID = rs.getInt("uID");
    58. reply.username = new UserDao().selectUserNameByUid(reply.uID);
    59. reply.rTopic = rs.getString("rTopic");
    60. reply.rContent = rs.getString("rContent");
    61. String Time = rs.getString("rTime");
    62. reply.rTime = Time.substring(0,Time.length()-5);
    63. reply.rClickCount = rs.getInt("rClickCount");
    64. list.add(reply);
    65. }
    66. }
    67. }
    68. }
    69. return list;
    70. }
    71. // 插入主贴
    72. @SneakyThrows
    73. public void insert(int tid, Integer uID, String content) {
    74. try (Connection c = DBUtil.connection()){
    75. String sql = "insert into reply (tID,uID,rContent) values (?,?,?)";
    76. try (PreparedStatement ps = c.prepareStatement(sql)){
    77. ps.setInt(1,tid);
    78. ps.setInt(2,uID);
    79. ps.setString(3,content);
    80. ps.executeUpdate();
    81. System.out.println("插入完成");
    82. }
    83. }
    84. }
    85. }

    3.5 KeyDao

    1. package forum.dao;
    2. import forum.model.Keyword;
    3. import forum.util.DBUtil;
    4. import lombok.SneakyThrows;
    5. import java.sql.Connection;
    6. import java.sql.PreparedStatement;
    7. import java.sql.ResultSet;
    8. /**
    9. * @author haomin
    10. * @date 2022/07/04 10:11
    11. **/
    12. public class KeyDao {
    13. // 插入查询的关键字
    14. @SneakyThrows
    15. public void insertKey (String keyword){
    16. String sql = "INSERT INTO `forum_management_information_system`.`key` (`keyword`) VALUES (?);";
    17. try (Connection c = DBUtil.connection()){
    18. try (PreparedStatement ps = c.prepareStatement(sql)){
    19. ps.setString(1,keyword);
    20. ps.executeUpdate();
    21. System.out.println("插入完成");
    22. }
    23. }
    24. }
    25. // 更新主贴回复数
    26. @SneakyThrows
    27. public void updateTReplyCount(int tID, int count) {
    28. String sql = "update topic set tReplyCount = ? where tID = ?";
    29. try (Connection c = DBUtil.connection()) {
    30. try (PreparedStatement ps = c.prepareStatement(sql)) {
    31. ps.setInt(1,count);
    32. ps.setInt(2,tID);
    33. ps.executeUpdate();
    34. }
    35. }
    36. }
    37. // 查询是否存在关键字
    38. @SneakyThrows
    39. public String selectKey () {
    40. String sql = "select keyword from forum_management_information_system.key;";
    41. try (Connection c = DBUtil.connection()){
    42. try (PreparedStatement ps = c.prepareStatement(sql)){
    43. try (ResultSet rs = ps.executeQuery()){
    44. if(rs.next()){
    45. String keyword = rs.getString("keyword");
    46. return keyword;
    47. }else {
    48. return null;
    49. }
    50. }
    51. }
    52. }
    53. }
    54. // 删除关键字
    55. @SneakyThrows
    56. public void deleteKey () {
    57. String sql = "DELETE FROM `forum_management_information_system`.`key` WHERE (1 = 1);";
    58. try (Connection c = DBUtil.connection()){
    59. try (PreparedStatement ps = c.prepareStatement(sql)){
    60. ps.executeUpdate();
    61. }
    62. }
    63. }
    64. }

    三. 约定前后端交互接口

    0. 前端页面

    先把前端页面拷贝到当前项目

    前端页面可见于上一篇博客:《前端项目 - 论坛信息管理系统(纯页面)》

    1. 实现论坛列表页

    1.1约定前后端交互接口

    1. {
    2. "currentUser" : {
    3. "uID" : 17,
    4. "username" : "张三",
    5. "password" : "123",
    6. "userSex" : "男",
    7. "userAge" : 18,
    8. "userOccupation" : "大数据开发工程师",
    9. "userHobby" : "敲代码",
    10. "userPoint" : 1,
    11. "userClass" : 1,
    12. "userRegister" : "2022-07-08 15:01",
    13. "uid" : 17
    14. },
    15. "pointCount" : 1,
    16. "classCount" : 1,
    17. "sectionList" : [ {
    18. "sID" : 12,
    19. "uID" : 1,
    20. "sName" : "网易云",
    21. "sStatement" : "小时候枕头上全是口水,长大后枕头上全是泪水;小时候微笑是一个心情,长大后微笑是一种表情;小时候哭着哭着就笑了,长大后笑着笑着就哭了。我们终于到了小时候最羡慕的年龄,但却没有成为小时候最想成为的人。——网易云音乐热评《当我已不再那么年轻》",
    22. "sClickCount" : 2,
    23. "sTopicCount" : 3,
    24. "uid" : 1,
    25. "sname" : "网易云",
    26. "sclickCount" : 2,
    27. "sstatement" : "小时候枕头上全是口水,长大后枕头上全是泪水;小时候微笑是一个心情,长大后微笑是一种表情;小时候哭着哭着就笑了,长大后笑着笑着就哭了。我们终于到了小时候最羡慕的年龄,但却没有成为小时候最想成为的人。——网易云音乐热评《当我已不再那么年轻》"
    28. "sid" : 12,
    29. "stopicCount" : 3
    30. }, ...]
    31. "topicList" : null
    32. }

    1.2 实现服务器代码

    1. package forum.servlet;
    2. import com.fasterxml.jackson.databind.ObjectMapper;
    3. import forum.dao.KeyDao;
    4. import forum.model.Keyword;
    5. import forum.model.SectionListResult;
    6. import forum.model.User;
    7. import forum.service.SectionService;
    8. import javax.servlet.ServletException;
    9. import javax.servlet.annotation.WebServlet;
    10. import javax.servlet.http.HttpServlet;
    11. import javax.servlet.http.HttpServletRequest;
    12. import javax.servlet.http.HttpServletResponse;
    13. import javax.servlet.http.HttpSession;
    14. import java.io.IOException;
    15. /**
    16. * @author haomin
    17. * @date 2022/06/30 11:21
    18. **/
    19. @WebServlet("/section-list.json")
    20. public class SectionListJsonServlet extends HttpServlet {
    21. @Override
    22. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    23. User currentUser = null;
    24. Keyword key = null;
    25. System.out.println("开始");
    26. HttpSession session = req.getSession(false);
    27. if(session != null){
    28. currentUser = (User) session.getAttribute("currentUser");
    29. }
    30. String keyword = new KeyDao().selectKey();
    31. SectionService sectionService = new SectionService();
    32. SectionListResult result = null;
    33. if(keyword == null) {
    34. result = sectionService.sectionListResult(currentUser);
    35. System.out.println("执行第一个");
    36. }else {
    37. System.out.println(keyword);
    38. result = sectionService.sectionListResult(currentUser,keyword);
    39. System.out.println("执行第二个");
    40. }
    41. ObjectMapper objectMapper = new ObjectMapper();
    42. String jsonString = objectMapper.writeValueAsString(result);
    43. resp.setCharacterEncoding("utf-8");
    44. resp.setContentType("application/json");
    45. resp.getWriter().printf(jsonString);
    46. }
    47. }

    1.3 编写客户端代码

    1. // 1. request /json/article_list.json
    2. // 2. update dom tree
    3. function renderAuthor(currentUser) {
    4. document.querySelector('.author-username').textContent = currentUser.username
    5. document.querySelector('.author-userSex').textContent = currentUser.userSex
    6. document.querySelector('.author-userAge').textContent = currentUser.userAge
    7. document.querySelector('.author-userOccupation').textContent = currentUser.userOccupation
    8. document.querySelector('.author-userHobby').textContent = "爱好:" + currentUser.userHobby
    9. }
    10. function renderCount(pointCount, classCount) {
    11. document.querySelector('.author-userPoint').textContent = pointCount
    12. document.querySelector('.author-userClass').textContent = classCount
    13. }
    14. function renderSectionList(sectionList, topicList) {
    15. console.log(sectionList)
    16. var container = document.querySelector('.section')
    17. console.log(container)
    18. for (var i in sectionList) {
    19. var section = sectionList[i]
    20. console.log(section)
    21. var html = `
    22. ` +
  • `
    ` +
  • `

    ${section.sName}

    `
    +
  • `
    版块ID: ${section.sID}
    `
    +
  • `

    ${section.sStatement}

    `
    +
  • `
    ` +
  • `
    ` +
  • `
    浏览量
    `
    +
  • `
    ${section.sClickCount}
    `
    +
  • `
    ` +
  • `
    ` +
  • `
    主贴数
    `
    +
  • `
    ${section.sTopicCount}
    `
    +
  • `
    ` +
  • `
    ` +
  • `
    ` +
  • `
    ` +
  • `
  • `
  • container.innerHTML += html
  • }
  • }
  • function renderTopicList(topicList) {
  • console.log(topicList)
  • var container = document.querySelector('.topic')
  • console.log(container)
  • for (var i in topicList) {
  • var topic = topicList[i]
  • console.log(topic)
  • var html = `
  • ` +
  • `
    ` +
  • `

    ${topic.tTopic}

    `
    +
  • `

    ${topic.tTime}

    `
    +
  • `
    贴主: ${topic.username}
    `
    +
  • `

    ${topic.tContent}

    `
    +
  • `
    ` +
  • `
    ` +
  • `
    浏览量
    `
    +
  • `
    ${topic.tClickCount}
    `
    +
  • `
    ` +
  • `
    ` +
  • `
    回复
    `
    +
  • `
    ${topic.tReplyCount}
    `
    +
  • `
    ` +
  • `
    ` +
  • `
    text-align: center;color: black;user-select: none;cursor: pointer;">` +
  • `
    ` +
  • `
  • `
  • container.innerHTML += html
  • }
  • }
  • var xhr = new XMLHttpRequest()
  • xhr.open('get', '/section-list.json')
  • xhr.onload = function() {
  • //alert(this.responseText);
  • var data = JSON.parse(this.responseText)
  • if(!data.currentUser){
  • // 重定向
  • // location = '/login.html'
  • location.assign('/login.html')
  • return
  • }
  • renderAuthor(data.currentUser)
  • renderCount(data.pointCount, data.classCount)
  • renderSectionList(data.sectionList)
  • renderTopicList(data.topicList)
  • }
  • xhr.send()
  • 实现效果:

    2. 实现论坛主贴页

    2.1约定前后端交互接口

    1. {
    2. "currentUser" : {
    3. "uID" : 17,
    4. "username" : "张三",
    5. "password" : "123",
    6. "userSex" : "男",
    7. "userAge" : 18,
    8. "userOccupation" : "大数据开发工程师",
    9. "userHobby" : "敲代码",
    10. "userPoint" : 1,
    11. "userClass" : 1,
    12. "userRegister" : "2022-07-08 15:01",
    13. "uid" : 17
    14. },
    15. "pointCount" : 1,
    16. "classCount" : 1,
    17. "topicList" : [ {
    18. "tID" : 16,
    19. "sID" : 12,
    20. "uID" : 11,
    21. "username" : "管理员",
    22. "tTopic" : "窃取天上三分景",
    23. "tContent" : "小狐狸想去人间很久了,临行之前,她的姥姥赠她了一件宝物芙蓉面。 小狐狸得了这芙蓉面,欢喜极了,她摸了摸芙蓉面道:“姥姥,我得了芙蓉面也能行走人世吗?” “是啊,只要你戴上芙蓉面,这世上任何人的脸,都可以幻化,可你是妖,就算有了芙蓉面,也得学世人的姿态。” 小狐狸拿着芙蓉面思索半天,",
    24. "tTime" : "2022-07-08 13:50",
    25. "tReplyCount" : 4,
    26. "tClickCount" : 4,
    27. "uid" : 11,
    28. "treplyCount" : 4,
    29. "tclickCount" : 4,
    30. "ttime" : "2022-07-08 13:50",
    31. "tid" : 16,
    32. "tcontent" : "小狐狸想去人间很久了,临行之前,她的姥姥赠她了一件宝物芙蓉面。 小狐狸得了这芙蓉面,欢喜极了,她摸了摸芙蓉面道:“姥姥,我得了芙蓉面也能行走人世吗?” “是啊,只要你戴上芙蓉面,这世上任何人的脸,都可以幻化,可你是妖,就算有了芙蓉面,也得学世人的姿态。” 小狐狸拿着芙蓉面思索半天,",
    33. "ttopic" : "窃取天上三分景",
    34. "sid" : 12
    35. },...]
    36. }

    2.2 实现服务器代码

    1. package forum.servlet;
    2. import com.fasterxml.jackson.databind.ObjectMapper;
    3. import forum.dao.KeyDao;
    4. import forum.model.Keyword;
    5. import forum.model.SectionListResult;
    6. import forum.model.User;
    7. import forum.service.SectionService;
    8. import javax.servlet.ServletException;
    9. import javax.servlet.annotation.WebServlet;
    10. import javax.servlet.http.HttpServlet;
    11. import javax.servlet.http.HttpServletRequest;
    12. import javax.servlet.http.HttpServletResponse;
    13. import javax.servlet.http.HttpSession;
    14. import java.io.IOException;
    15. /**
    16. * @author haomin
    17. * @date 2022/06/30 11:21
    18. **/
    19. @WebServlet("/section-list.json")
    20. public class SectionListJsonServlet extends HttpServlet {
    21. @Override
    22. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    23. User currentUser = null;
    24. Keyword key = null;
    25. System.out.println("开始");
    26. HttpSession session = req.getSession(false);
    27. if(session != null){
    28. currentUser = (User) session.getAttribute("currentUser");
    29. }
    30. String keyword = new KeyDao().selectKey();
    31. SectionService sectionService = new SectionService();
    32. SectionListResult result = null;
    33. if(keyword == null) {
    34. result = sectionService.sectionListResult(currentUser);
    35. System.out.println("执行第一个");
    36. }else {
    37. System.out.println(keyword);
    38. result = sectionService.sectionListResult(currentUser,keyword);
    39. System.out.println("执行第二个");
    40. }
    41. ObjectMapper objectMapper = new ObjectMapper();
    42. String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);
    43. resp.setCharacterEncoding("utf-8");
    44. resp.setContentType("application/json");
    45. resp.getWriter().printf(jsonString);
    46. }
    47. }

    2.3 编写客户端代码

    1. // 1. request /json/article_list.json
    2. // 2. update dom tree
    3. function renderAuthor(currentUser) {
    4. document.querySelector('.author-username').textContent = currentUser.username
    5. document.querySelector('.author-userSex').textContent = currentUser.userSex
    6. document.querySelector('.author-userAge').textContent = currentUser.userAge
    7. document.querySelector('.author-userOccupation').textContent = currentUser.userOccupation
    8. document.querySelector('.author-userHobby').textContent = "爱好:" + currentUser.userHobby
    9. }
    10. function renderCount(pointCount, classCount) {
    11. document.querySelector('.author-userPoint').textContent = pointCount
    12. document.querySelector('.author-userClass').textContent = classCount
    13. }
    14. function renderTopicList(topicList) {
    15. console.log(topicList)
    16. var container = document.querySelector('.topic')
    17. console.log(container)
    18. for (var i in topicList) {
    19. var topic = topicList[i]
    20. console.log(topic)
    21. var html = `
    22. ` +
    23. `
      ` +
    24. `

      ${topic.tTopic}

      `
      +
    25. `

      ${topic.tTime}

      `
      +
    26. `
      贴主: ${topic.username}
      `
      +
    27. `

      ${topic.tContent}

      `
      +
    28. `
      ` +
    29. `
      ` +
    30. `
      浏览量
      `
      +
    31. `
      ${topic.tClickCount}
      `
      +
    32. `
      ` +
    33. `
      ` +
    34. `
      回复
      `
      +
    35. `
      ${topic.tReplyCount}
      `
      +
    36. `
      ` +
    37. `
      ` +
    38. `
      text-align: center;color: black;user-select: none;cursor: pointer;">` +
    39. `
      ` +
    40. `
    41. `
    42. container.innerHTML += html
    43. }
    44. }
    45. var xhr = new XMLHttpRequest()
    46. xhr.open('get', '/topic-list.json' + location.search)
    47. xhr.onload = function() {
    48. // 打印 json内容
    49. alert(this.responseText);
    50. console.log(this.responseText)
    51. var data = JSON.parse(this.responseText)
    52. if(!data.currentUser){
    53. // 重定向
    54. // location = '/login.html'
    55. location.assign('/login.html')
    56. return
    57. }
    58. renderAuthor(data.currentUser)
    59. renderCount(data.pointCount, data.classCount)
    60. renderTopicList(data.topicList)
    61. }
    62. xhr.send()

    实现效果:

    3. 实现论坛回复页

    3.1约定前后端交互接口

    1. {
    2. "currentUser" : {
    3. "uID" : 17,
    4. "username" : "张三",
    5. "password" : "123",
    6. "userSex" : "男",
    7. "userAge" : 18,
    8. "userOccupation" : "大数据开发工程师",
    9. "userHobby" : "敲代码",
    10. "userPoint" : 1,
    11. "userClass" : 1,
    12. "userRegister" : "2022-07-08 15:01",
    13. "uid" : 17
    14. },
    15. "pointCount" : 1,
    16. "classCount" : 1,
    17. "replyList" : [ {
    18. "rID" : 39,
    19. "tID" : 16,
    20. "uID" : 17,
    21. "username" : "张三",
    22. "rTopic" : "回帖",
    23. "rContent" : "hello word",
    24. "rTime" : "2022-07-08 15:04",
    25. "rClickCount" : 0
    26. }, {
    27. "rID" : 32,
    28. "tID" : 16,
    29. "uID" : 11,
    30. "username" : "管理员",
    31. "rTopic" : "回帖",
    32. "rContent" : "有些人为了上前排连尊严都不要了,您怎么看呢?父亲?",
    33. "rTime" : "2022-07-08 13:54",
    34. "rClickCount" : 0
    35. }],
    36. "tid" : 16,
    37. "topic" : {
    38. "tID" : 16,
    39. "sID" : 12,
    40. "uID" : 11,
    41. "username" : "管理员",
    42. "tTopic" : "窃取天上三分景",
    43. "tContent" : "小狐狸想去人间很久了,临行之前,她的姥姥赠她了一件宝物芙蓉面。 小狐狸得了这芙蓉面,欢喜极了,她摸了摸芙蓉面道:“姥姥,我得了芙蓉面也能行走人世吗?” “是啊,只要你戴上芙蓉面,这世上任何人的脸,都可以幻化,可你是妖,就算有了芙蓉面,也得学世人的姿态。” 小狐狸拿着芙蓉面思索半天,",
    44. "tTime" : "2022-07-08 13:50",
    45. "tReplyCount" : 4,
    46. "tClickCount" : 6,
    47. "uid" : 11,
    48. "treplyCount" : 4,
    49. "tclickCount" : 6,
    50. "ttime" : "2022-07-08 13:50",
    51. "tid" : 16,
    52. "tcontent" : "小狐狸想去人间很久了,临行之前,她的姥姥赠她了一件宝物芙蓉面。 小狐狸得了这芙蓉面,欢喜极了,她摸了摸芙蓉面道:“姥姥,我得了芙蓉面也能行走人世吗?” “是啊,只要你戴上芙蓉面,这世上任何人的脸,都可以幻化,可你是妖,就算有了芙蓉面,也得学世人的姿态。” 小狐狸拿着芙蓉面思索半天,",
    53. "ttopic" : "窃取天上三分景",
    54. "sid" : 12
    55. }
    56. }

    3.2 实现服务器代码

    1. package forum.servlet;
    2. import com.fasterxml.jackson.databind.ObjectMapper;
    3. import forum.dao.TopicDao;
    4. import forum.model.ReplyListResult;
    5. import forum.model.User;
    6. import forum.service.ReplyService;
    7. import javax.servlet.ServletException;
    8. import javax.servlet.annotation.WebServlet;
    9. import javax.servlet.http.HttpServlet;
    10. import javax.servlet.http.HttpServletRequest;
    11. import javax.servlet.http.HttpServletResponse;
    12. import javax.servlet.http.HttpSession;
    13. import java.io.IOException;
    14. /**
    15. * @author haomin
    16. * @date 2022/07/01 17:05
    17. **/
    18. @WebServlet("/reply-list.json")
    19. public class ReplyListServlet extends HttpServlet {
    20. @Override
    21. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    22. req.setCharacterEncoding("utf-8");
    23. String tidString = req.getParameter("tid");
    24. int tid = Integer.parseInt(tidString);
    25. User currentUser = null;
    26. HttpSession session = req.getSession(false);
    27. if(session != null){
    28. currentUser = (User)session.getAttribute("currentUser");
    29. }
    30. // 浏览一次回帖页面,浏览次数加1
    31. new TopicDao().update(tid);
    32. ReplyService replyService = new ReplyService();
    33. ReplyListResult result = replyService.replyListResult(currentUser,tid);
    34. result.tid = tid;
    35. ObjectMapper objectMapper = new ObjectMapper();
    36. String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);
    37. resp.setCharacterEncoding("utf-8");
    38. resp.setContentType("application/json");
    39. resp.getWriter().println(jsonString);
    40. }
    41. }

    3.3 编写客户端代码

    1. function renderAuthor(currentUser) {
    2. document.querySelector('.author-username').textContent = currentUser.username
    3. document.querySelector('.author-userSex').textContent = currentUser.userSex
    4. document.querySelector('.author-userAge').textContent = currentUser.userAge
    5. document.querySelector('.author-userOccupation').textContent = currentUser.userOccupation
    6. document.querySelector('.author-userHobby').textContent = "爱好:" + currentUser.userHobby
    7. }
    8. function renderCount(pointCount, classCount) {
    9. document.querySelector('.author-userPoint').textContent = pointCount
    10. document.querySelector('.author-userClass').textContent = classCount
    11. }
    12. function renderDefineTid(tid){
    13. document.querySelector('.tid').value = tid;
    14. }
    15. function renderReplyList(topic,replyList){
    16. console.log(replyList)
    17. var container = document.querySelector('.reply')
    18. console.log(container)
    19. // 主贴
    20. var html = `
    21. ` +
    22. `
      ` +
    23. `

      ${topic.tTopic}

      `
      +
    24. `

      ${topic.tTime}

      `
      +
    25. `
      贴主: ${topic.username}
      `
      +
    26. `

      ${topic.tContent}

      `
      +
    27. `
      ` +
    28. `
      ` +
    29. `
      浏览量
      `
      +
    30. `
      ${topic.tClickCount}
      `
      +
    31. `
      ` +
    32. `
      ` +
    33. `
    34. `
    35. container.innerHTML += html
    36. //回帖
    37. for(var i in replyList){
    38. var reply = replyList[i]
    39. console.log(reply)
    40. var html = `
    41. ` +
    42. `
      ` +
    43. `

      ${reply.rTopic}

      `
      +
    44. `

      ${reply.rTime}

      `
      +
    45. `
      ${reply.username}
      `
      +
    46. `

      ${reply.rContent}

      `
      +
    47. /*`
      ` +
    48. `
      ` +
    49. `
      点击次数
      ` +
    50. `
      100
      ` +
    51. `
      ` +
    52. `
      ` +*/
    53. `
    54. `
    55. container.innerHTML += html
    56. }
    57. }
    58. var xhr = new XMLHttpRequest()
    59. xhr.open('get','/reply-list.json' + location.search)
    60. xhr.onload = function() {
    61. //alert(this.responseText);
    62. console.log(this.responseText)
    63. var data = JSON.parse(this.responseText)
    64. if(!data.currentUser){
    65. location.assign('/login.html')
    66. return
    67. }
    68. renderAuthor(data.currentUser)
    69. renderCount(data.pointCount, data.classCount)
    70. renderReplyList(data.topic,data.replyList)
    71. renderDefineTid(data.tid)
    72. }
    73. xhr.send()

    实现效果:

    4. 实现论坛个人中心页

    4.1约定前后端交互接口

    个人中心的json数据来自于/section-list.json

    1. {
    2. "currentUser" : {
    3. "uID" : 17,
    4. "username" : "张三",
    5. "password" : "123",
    6. "userSex" : "男",
    7. "userAge" : 18,
    8. "userOccupation" : "大数据开发工程师",
    9. "userHobby" : "敲代码",
    10. "userPoint" : 1,
    11. "userClass" : 1,
    12. "userRegister" : "2022-07-08 15:01",
    13. "uid" : 17
    14. }
    15. }

    4.2 实现服务器代码

    个人中心的服务器代码来自于/section-list.json,和列表页服务器代码相同,再次不在赘述。

    4.3 编写客户端代码

    1. function renderAuthor(currentUser) {
    2. document.querySelector('.author-username').value = currentUser.username
    3. document.querySelector('.author-userSex').value = currentUser.userSex
    4. document.querySelector('.author-userAge').value = currentUser.userAge
    5. document.querySelector('.author-userOccupation').value = currentUser.userOccupation
    6. document.querySelector('.author-userHobby').value = currentUser.userHobby
    7. document.querySelector('.author-userPoint').value = currentUser.userPoint
    8. document.querySelector('.author-userClass').value = currentUser.userClass
    9. document.querySelector('.author-userRegister').value = currentUser.userRegister
    10. }
    11. var xhr = new XMLHttpRequest()
    12. xhr.open('get', '/section-list.json')
    13. xhr.onload = function() {
    14. //alert(this.responseText);
    15. var data = JSON.parse(this.responseText)
    16. if(!data.currentUser){
    17. // 重定向
    18. // location = '/login.html'
    19. location.assign('/login.html')
    20. return
    21. }
    22. renderAuthor(data.currentUser)
    23. }
    24. xhr.send()

    实现效果:

    5. 实现论坛发布帖子页

    5.1约定前后端交互接口

    [请求] post /editor.do

    5.2 实现服务器代码

    1. package forum.servlet;
    2. import forum.dao.TopicDao;
    3. import forum.model.User;
    4. import javax.servlet.ServletException;
    5. import javax.servlet.annotation.WebServlet;
    6. import javax.servlet.http.HttpServlet;
    7. import javax.servlet.http.HttpServletRequest;
    8. import javax.servlet.http.HttpServletResponse;
    9. import javax.servlet.http.HttpSession;
    10. import java.io.IOException;
    11. /**
    12. * @author haomin
    13. * @date 2022/07/01 19:30
    14. **/
    15. @WebServlet("/editor.do")
    16. public class EditorDoServlet extends HttpServlet {
    17. @Override
    18. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    19. req.setCharacterEncoding("utf-8");
    20. String title = req.getParameter("title");
    21. String sidString = req.getParameter("type");
    22. int sid = Integer.parseInt(sidString);
    23. String content = req.getParameter("editor-markdown-doc");
    24. User currentUser = null;
    25. HttpSession session = req.getSession(false);
    26. if (session != null) {
    27. currentUser = (User) session.getAttribute("currentUser");
    28. }
    29. if (currentUser == null) {
    30. // 说明没有登录
    31. resp.sendRedirect("/login.html");
    32. return;
    33. }
    34. TopicDao topicDao = new TopicDao();
    35. topicDao.insert(sid,currentUser.uID,title,content);
    36. // 重定向到文章详情页
    37. resp.sendRedirect("/detail.html?sid=" + sid);
    38. }
    39. }

     5.3 编写客户端代码

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>写帖子title>
    6. <link rel="stylesheet" href="css/navigation bar.css">
    7. <link rel="stylesheet" href="css/editor.css">
    8. head>
    9. <body>
    10. <div class="导航栏">
    11. <div class="left-logo">
    12. <div class="logo"><img src="img/系统图标.png" width="45">div>
    13. <p>论坛管理信息系统p>
    14. div>
    15. <div class="占位">div>
    16. <div class="right-function">
    17. <a href="center.html">个人中心a>
    18. <a href="list.html">主页a>
    19. <a href="editor.html">写帖子a>
    20. <a href="logout" target="_self">注销a>
    21. div>
    22. div>
    23. <div class="blog-edit-container">
    24. <form method="post" action="/editor.do">
    25. <div class="title">
    26. <input type="text" placeholder="在这里写下主贴标题" id="title" name="title">
    27. <input type="text" placeholder="板块编号" id="type" name="type" style=" height: 40px;
    28. width: 80px;
    29. text-indent: 10px;
    30. border-radius: 10px;
    31. outline: none;
    32. border: none;
    33. background-color:rgba(255, 255, 255, 0.8);">
    34. <button id="submit">发布帖子button>
    35. div>
    36. <div id="editor" class="编辑器">div>
    37. <link rel="stylesheet" href="editor.md/css/editormd.min.css" />
    38. <script src="js/jquery.min.js">script>
    39. <script src="editor.md/lib/marked.min.js">script>
    40. <script src="editor.md/lib/prettify.min.js">script>
    41. <script src="editor.md/editormd.js">script>
    42. form>
    43. div>
    44. <script>
    45. var content = '# 在这里写下一篇帖子 ##';
    46. var config = {
    47. // 这里的尺寸必须在这里设置. 设置样式会被 editormd 自动覆盖掉.
    48. width: "100%",
    49. // 高度 100% 意思是和父元素一样高. 要在父元素的基础上去掉标题编辑区的高度
    50. height: "100vh",
    51. // 编辑器中的初始内容
    52. markdown: content,
    53. // 指定 editor.md 依赖的插件路径
    54. path: "editor.md/lib/"
    55. };
    56. editormd("editor", config);
    57. script>
    58. body>
    59. html>

    实现效果:

    6. 实现论坛登录页

    6.1约定前后端交互接口

    [请求] post /login.do

    6.2 实现服务器代码

    1. package forum.servlet;
    2. import forum.dao.UserDao;
    3. import forum.model.User;
    4. import javax.servlet.ServletException;
    5. import javax.servlet.annotation.WebServlet;
    6. import javax.servlet.http.HttpServlet;
    7. import javax.servlet.http.HttpServletRequest;
    8. import javax.servlet.http.HttpServletResponse;
    9. import javax.servlet.http.HttpSession;
    10. import java.io.IOException;
    11. /**
    12. * @author haomin
    13. * @date 2022/06/29 17:18
    14. **/
    15. @WebServlet("/login.do")
    16. public class LoginDoServlet extends HttpServlet {
    17. @Override
    18. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    19. req.setCharacterEncoding("utf-8");
    20. String username = req.getParameter("username");
    21. String password = req.getParameter("password");
    22. System.out.println("DEBUG: username = " + username);
    23. System.out.println("DEBUG: password = " + password);
    24. UserDao userDao = new UserDao();
    25. User user = userDao.selectOneByUsernameAndPassword(username,password);
    26. if(user == null){
    27. resp.sendRedirect("/login.html");
    28. return;
    29. }
    30. System.out.println(user);
    31. HttpSession session = req.getSession();
    32. session.setAttribute("currentUser",user);
    33. resp.sendRedirect("/");
    34. }
    35. }

    6.3 编写客户端代码

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>登录title>
    6. <link rel="stylesheet" href="css/navigation bar.css">
    7. <link rel="stylesheet" href="css/login.css">
    8. head>
    9. <body>
    10. <div class="导航栏">
    11. <div class="left-logo">
    12. <div class="logo"><img src="img/系统图标.png" width="45">div>
    13. <p>论坛管理信息系统p>
    14. div>
    15. <div class="占位">div>
    16. <div class="right-function">
    17. <span class="center">span>
    18. <a href="list.html">主页a>
    19. <a href="editor.html" target="_blank">写帖子a>
    20. <a href="logon.html">注册a>
    21. div>
    22. div>
    23. <div class="主体区">
    24. <div class="登录框">
    25. <form action="/login.do" method="post">
    26. <h2>登录h2>
    27. <div>
    28. <span>用户名span>
    29. <input type="text" class="text" name="username" placeholder="请输入用户名">
    30. div>
    31. <div>
    32. <span>密码span>
    33. <input type="password" class="text" name="password" placeholder="请输入密码">
    34. div>
    35. <div>
    36. <button class="提交">登录button>
    37. div>
    38. form>
    39. div>
    40. div>
    41. body>
    42. html>

     实现效果:

    7. 实现论坛注册页

    7.1约定前后端交互接口

    [请求] post /logon.do

    7.2 实现服务器代码

    1. package forum.servlet;
    2. import forum.dao.UserDao;
    3. import forum.model.User;
    4. import javax.servlet.ServletException;
    5. import javax.servlet.annotation.WebServlet;
    6. import javax.servlet.http.HttpServlet;
    7. import javax.servlet.http.HttpServletRequest;
    8. import javax.servlet.http.HttpServletResponse;
    9. import javax.servlet.http.HttpSession;
    10. import java.io.IOException;
    11. /**
    12. * @author haomin
    13. * @date 2022/07/03 08:34
    14. **/
    15. @WebServlet("/logon.do")
    16. public class LogonDoServlet extends HttpServlet {
    17. @Override
    18. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    19. req.setCharacterEncoding("utf-8");
    20. String username = req.getParameter("username");
    21. String sex = req.getParameter("sex");
    22. String age = req.getParameter("age");
    23. String occupation = req.getParameter("occupation");
    24. String hobby = req.getParameter("hobby");
    25. String password1 = req.getParameter("password1");
    26. String password2 = req.getParameter("password2");
    27. UserDao userDao = new UserDao();
    28. User user = userDao.insert(username,password1,sex,Integer.parseInt(password1),occupation,hobby);
    29. HttpSession session = req.getSession();
    30. session.setAttribute("currentUser",user);
    31. resp.sendRedirect("/");
    32. }
    33. }

    7.3 编写客户端代码

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>注册title>
    6. <link rel="stylesheet" href="css/navigation bar.css">
    7. <link rel="stylesheet" href="css/logon.css">
    8. head>
    9. <body>
    10. <div class="导航栏">
    11. <div class="left-logo">
    12. <div class="logo"><img src="img/系统图标.png" width="45">div>
    13. <p>论坛管理信息系统p>
    14. div>
    15. <div class="占位">div>
    16. <div class="right-function">
    17. <span class="center">span>
    18. <a href="list.html">主页a>
    19. <a href="editor.html" target="_blank">写帖子a>
    20. <a href="login.html">登录a>
    21. div>
    22. div>
    23. <div class="主体区">
    24. <div class="注册框">
    25. <form action="/logon.do" method="post">
    26. <h2>注册h2>
    27. <div>
    28. <span>昵称span>
    29. <input type="text" class="text" placeholder="请输入昵称" name="username">
    30. div>
    31. <div>
    32. <span>年龄span>
    33. <input type="text" class="text" placeholder="请输入年龄" name="age">
    34. div>
    35. <div>
    36. <span>性别span>
    37. <input type="text" class="text" placeholder="请输入性别 男|女" name="sex">
    38. div>
    39. <div>
    40. <span>爱好span>
    41. <input type="text" class="text" placeholder="请输入爱好" name="hobby">
    42. div>
    43. <div>
    44. <span>职业span>
    45. <input type="text" class="text" placeholder="请输入职业" name="occupation">
    46. div>
    47. <div>
    48. <span>密码span>
    49. <input type="password" class="text" placeholder="请输入密码" name="password1">
    50. div>
    51. <div>
    52. <span>再次确认密码span>
    53. <input type="password" class="text" placeholder="请再次确认密码" name="password2">
    54. div>
    55. <div>
    56. <button class="提交">注册button>
    57. div>
    58. form>
    59. div>
    60. div>
    61. body>
    62. html>

    实现效果:

    8. 实现论坛注销

    8.1实现服务器代码

    1. package forum.servlet;
    2. import javax.servlet.ServletException;
    3. import javax.servlet.annotation.WebServlet;
    4. import javax.servlet.http.HttpServlet;
    5. import javax.servlet.http.HttpServletRequest;
    6. import javax.servlet.http.HttpServletResponse;
    7. import javax.servlet.http.HttpSession;
    8. import java.io.IOException;
    9. @WebServlet("/logout")
    10. public class LogoutServlet extends HttpServlet {
    11. @Override
    12. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    13. HttpSession session = req.getSession(false);
    14. if (session != null) {
    15. session.removeAttribute("currentUser");
    16. }
    17. resp.sendRedirect("/");
    18. }
    19. }
    1. package forum.servlet;
    2. import javax.servlet.ServletException;
    3. import javax.servlet.annotation.WebServlet;
    4. import javax.servlet.http.HttpServlet;
    5. import javax.servlet.http.HttpServletRequest;
    6. import javax.servlet.http.HttpServletResponse;
    7. import java.io.IOException;
    8. /**
    9. * @author haomin
    10. * @date 2022/06/30 08:43
    11. **/
    12. @WebServlet("")
    13. public class IndexServlet extends HttpServlet {
    14. @Override
    15. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    16. resp.sendRedirect("/list.html");
    17. }
    18. }

    重定向到论坛主页,但是服务器发现没有用户登录,继而重定向到用户登录页。

    实现效果:

     论坛信息管理系统主要重点就介绍到这里了,如果想看看项目源码,可以点击这里:《论坛信息管理系统》

    如果你喜欢这篇文章,请点赞加关注吧,或者如果你对与文章有什么困惑,可以私信我。

    🏓🏓🏓 

  • 相关阅读:
    学习Java这么久了,还没了解过Java虚拟机?这有点说不过去了啊,阿里P8总结最新Java虚拟机学习指南赶紧学起来!
    树莓派(香橙派)通过.NET IoT 操作SPI编写屏幕驱动 顺手做个四足机器人(一)
    NGINX源码之:listen和server_name命令与listening监听创建
    电子证据的固定方法研究
    Java学习笔记3.5.2 继承 - 方法的重写
    企业数字化进程的关键一步
    招标网站信息爬取
    用什么命令看Linux系统的体系架构
    CF1720 --- Codeforces Round #815 (Div. 2)
    VSCode查询包中的内容设置
  • 原文地址:https://blog.csdn.net/m0_62218217/article/details/125810816