【Spring Boot】Spring Boot实现完整论坛功能示例代码

以下是一个简单的Spring Boot论坛系统示例代码:

  1. 首先是数据库设计,我们创建以下几张表:
  • user表,存储用户信息,包括id、username、password、email、create_time等字段。
  • topic表,存储帖子信息,包括id、title、content、user_id、create_time等字段。
  • comment表,存储评论信息,包括id、content、user_id、topic_id、create_time等字段。
  1. 创建实体类

2.1 User实体类:

复制代码
`@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String username;

    @Column
    private String password;

    @Column
    private String email;

    @Column(name = "create_time")
    private Date createTime;

    // getter/setter省略
}
`

2.2 Topic实体类:

复制代码
`@Entity
@Table(name = "topic")
public class Topic {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String title;

    @Column
    private String content;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @Column(name = "create_time")
    private Date createTime;

    // getter/setter省略
}
`

2.3 Comment实体类:

复制代码
`@Entity
@Table(name = "comment")
public class Comment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String content;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "topic_id")
    private Topic topic;

    @Column(name = "create_time")
    private Date createTime;

    // getter/setter省略
}
`
  1. 创建Repository

3.1 UserRepository:

复制代码
`public interface UserRepository extends JpaRepository<User, Long> {

    User findByUsername(String username);

}
`

3.2 TopicRepository:

复制代码
`public interface TopicRepository extends JpaRepository<Topic, Long> {
}
`

3.3 CommentRepository:

复制代码
`public interface CommentRepository extends JpaRepository<Comment, Long> {
}
`
  1. 创建Service

4.1 UserService:

复制代码
`@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public boolean checkUser(User user) {
        User userInDb = userRepository.findByUsername(user.getUsername());
        if (userInDb != null && userInDb.getPassword().equals(user.getPassword())) {
            return true;
        } else {
            return false;
        }
    }

    public void saveUser(User user) {
        user.setCreateTime(new Date());
        userRepository.save(user);
    }

    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }
}
`

4.2 TopicService:

复制代码
`@Service
public class TopicService {

    @Autowired
    private TopicRepository topicRepository;

    public List<Topic> getAllTopics() {
        return topicRepository.findAll();
    }

    public Topic getTopicById(Long id) {
        return topicRepository.findById(id).orElse(null);
    }

    public void saveTopic(Topic topic) {
        topic.setCreateTime(new Date());
        topicRepository.save(topic);
    }

}
`

4.3 CommentService:

复制代码
`@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;

    public void saveComment(Comment comment) {
        comment.setCreateTime(new Date());
        commentRepository.save(comment);
    }

    public List<Comment> getCommentsByTopicId(Long topicId) {
        return commentRepository.findAllByTopicId(topicId);
    }
}
`
  1. 创建Controller

5.1 UserController:

复制代码
`@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    public String doLogin(User user, HttpSession session) {
        boolean result = userService.checkUser(user);
        if (result) {
            session.setAttribute("user", user);
            return "redirect:/";
        } else {
            return "login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/";
    }

    @GetMapping("/register")
    public String register() {
        return "register";
    }

    @PostMapping("/register")
    public String doRegister(User user) {
        userService.saveUser(user);
        return "redirect:/login";
    }
}
`

5.2 TopicController:

复制代码
`@Controller
public class TopicController {

    @Autowired
    private TopicService topicService;

    @Autowired
    private CommentService commentService;

    @GetMapping("/")
    public String index(Model model) {
        List<Topic> topics = topicService.getAllTopics();
        model.addAttribute("topics", topics);
        return "index";
    }

    @GetMapping("/topic/{id}")
    public String topic(@PathVariable Long id, Model model) {
        Topic topic = topicService.getTopicById(id);
        List<Comment> comments = commentService.getCommentsByTopicId(id);
        model.addAttribute("topic", topic);
        model.addAttribute("comments", comments);
        return "topic";
    }

    @GetMapping("/new-topic")
    public String newTopic() {
        return "new-topic";
    }

    @PostMapping("/new-topic")
    public String doNewTopic(Topic topic, HttpSession session) {
        User user = (User) session.getAttribute("user");
        topic.setUser(user);
        topicService.saveTopic(topic);
        return "redirect:/";
    }

}
`

5.3 CommentController:

复制代码
复制代码
`@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    @PostMapping("/new-comment")
    public String doNewComment(Comment comment, HttpSession session) {
        User user = (User) session.getAttribute("user");
        comment.setUser(user);
        commentService.saveComment(comment);
        return "redirect:/topic/" + comment.getTopic().getId();
    }

}
`
  1. 创建视图页面

6.1 index.html:

复制代码
复制代码
`<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>论坛首页</title>
</head>
<body>
    <h1>论坛首页</h1>
    <div>
        <a href="/new-topic">发表新帖</a>
    </div>
    <ul>
        <li th:each="topic : ${topics}">
            <a th:href="@{'/topic/' + ${topic.id}}"><h3 th:text="${topic.title}"></h3></a>
            <p th:text="${topic.content}"></p>
            <p>
                <span th:text="${topic.user.username}"></span>
                <span th:text="${#dates.format(topic.createTime, 'yyyy-MM-dd HH:mm:ss')}"></span>
            </p>
        </li>
    </ul>
</body>
</html>
`

6.2 topic.html:

复制代码
复制代码
`<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>话题详情</title>
</head>
<body>
    <h1 th:text="${topic.title}"></h1>
    <p th:text="${topic.content}"></p>
    <p>
        <span th:text="${topic.user.username}"></span>
        <span th:text="${#dates.format(topic.createTime, 'yyyy-MM-dd HH:mm:ss')}"></span>
    </p>
    <hr>
    <h2>评论</h2>
    <ul>
        <li th:each="comment : ${comments}">
            <p th:text="${comment.content}"></p>
            <p>
                <span th:text="${comment.user.username}"></span>
                <span th:text="${#dates.format(comment.createTime, 'yyyy-MM-dd HH:mm:ss')}"></span>
            </p>
        </li>
    </ul>
    <hr>
    <form action="/new-comment" method="post">
        <input type="hidden" name="topic.id" th:value="${topic.id}">
        <textarea name="content"></textarea>
        <br>
        <button type="submit">提交评论</button>
    </form>
</body>
</html>
`

6.3 new-topic.html:

复制代码
复制代码
`<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>发表新帖</title>
</head>
<body>
    <h1>发表新帖</h1>
    <form action="/new-topic" method="post">
        <input type="text" name="title">
        <br>
        <textarea name="content"></textarea>
        <br>
        <button type="submit">发布帖子</button>
    </form>
</body>
</html>
`

6.4 login.html:

复制代码
`<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
    <h1>登录</h1>
    <form action="/login" method="post">
        <input type="text" name="username">
`
相关推荐
努力成为包租婆4 分钟前
uniapp--原生插件开发
java·数据库·uni-app
海南java第二人1 小时前
Spring MVC核心流程深度解析:从请求到响应的完美掌控
java·springmvc
未来之窗软件服务1 小时前
幽冥大陆(一百10)PHP打造Java的Jar安全——东方仙盟筑基期
java·php·phar·仙盟创梦ide·东方仙盟
杜子不疼.1 小时前
【Linux】基础IO(二):系统文件IO
linux·运维·服务器
郝学胜-神的一滴1 小时前
深入理解网络IP协议与TTL机制:从原理到实践
linux·服务器·开发语言·网络·网络协议·tcp/ip·程序人生
松涛和鸣1 小时前
DAY61 IMX6ULL UART Serial Communication Practice
linux·服务器·网络·arm开发·数据库·驱动开发
程序猿_极客4 小时前
【2025 年最新版】Java JDK 安装与环境配置教程(附图文超详细,Windows+macOS 通用)
java·开发语言·windows·macos·jdk
猫头虎4 小时前
macOS 双开/多开微信WeChat完整教程(支持 4.X 及以上版本)
java·vscode·macos·微信·编辑器·mac·脚本
二哈喇子!7 小时前
BOM模型
开发语言·前端·javascript·bom
二哈喇子!7 小时前
Vue2 监听器 watcher
前端·javascript·vue.js