首页 > 解决方案 > Spring将评论实体添加到显示页面上的发布实体

问题描述

我想要一个 Post 实体,就像在堆栈溢出中一样:您有一个显示页面,您可以在其中看到某人发布的内容,但在下方您有评论字段。您不必被转移到完全不同的页面,例如 /post/id/addComment。我有 Post 实体:

public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Enumerated(value = EnumType.STRING)
    private Difficulty difficulty;

    @ManyToMany
    @JoinTable(name = "post_category",
            joinColumns = @JoinColumn(name = "post_id"),
            inverseJoinColumns = @JoinColumn(name = "category_id"))
    @Column(name = "categories")
    private List<Category> categories = new ArrayList<Category>();

    @Lob
    private Byte[] image;

    @OneToMany( mappedBy = "post",
            cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Comment> comments = new ArrayList<Comment>();

    private String text = "";
    private String author = "";
    private String description = "";
}

和评论实体:

public class Comment {

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

    @ManyToOne(
            fetch = FetchType.LAZY
    )
    @JoinColumn(name="post_id")
    Post post;

    private String text = "";
}

我有这样的帖子的html显示页面:

<p th:text="${post?.difficulty}"></p>
<p th:each="category : ${post?.categories}" th:text="${category?.text}"></p>
<p th:text="${post?.text}"></p>
<p th:text="${post?.author}"></p>
<p th:text="${post?.description}"></p>
<div>
    <p th:each="comment : ${post?.comments}" th:text="${comment?.text}"></p>
</div>
<div>
    <img src="../../static/images/tiger.jpg"
         th:src="@{'/post/' + ${post.id} + '/postimage'}"
         width="200" height="200">
</div>
<div>
    <form  th:object="${comment}" th:action="@{'/post/' + ${post.getId()} + '/comment'}"  method="post">
        <input type="hidden" th:field="*{id}"/>
        <p>Description: <input type="text" th:field="*{text}"/></p>

        <p><input type="submit" value="Submit" id="button" /> <input type="reset" value="Reset" /></p>
    </form>
</div>

你看到上面我列出了 Post 的类别、文本和其他字段。下面我添加了表单只是为了添加评论。它具有自动生成的隐藏 ID 值和用于填写输入的文本。提交后,我希望将其添加到评论存储库并分配给 Post。我发现的唯一解释是将用户重定向到“/addComment”等其他页面,然后进行 POST 操作,但这没有任何意义。转到完全其他页面只是为了添加评论?任何人都可以帮忙吗?谢谢

标签: javaspringspring-bootspring-mvcspring-data-jpa

解决方案


您可以首先重定向到 /post/{id}/addComment 并且对于功能控制器,您可以返回到 /post/{id} 如下所示

@PostMapping("/post/{id}/addComment")
public String addComment(@PathVariable int id, @ModelAtribute Comment comment){
...
...//perform add comment

return "redirect:/post"+id;
}

推荐阅读