【发布时间】:2021-04-15 04:45:51
【问题描述】:
我有一个班级帖子
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany
@JoinTable(name = "post_category",
joinColumns = @JoinColumn(name = "post_id"),
inverseJoinColumns = @JoinColumn(name = "category_id"))
private List<Category> categories = new ArrayList<Category>();
我还有其他字符串字段,但这并不重要。类别是:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany(mappedBy = "categories")
private List<Post> posts = new ArrayList<>();
我想发布一个 Post 实体。但是我在 Post 类中的 Category 字段有问题。
<div th:field="${post.categories}">
<div th:each="category,iter : ${categories}">
<input type="checkbox" id=${iter.index} name=${"category"+"["+iter.index+"]"} value=${category.text}>
<label for=${iter.index}> The category</label><br>
</div>
</div>
我想在后表单 html 中有一个带有类别的复选框列表。如果单击(选中)该类别,我希望将其添加到 Post Class 中的类别列表中。然而它不会发生。在控制器类中,当我在提交后返回 Post 类时,我什至在表单的字段中都没有类别。这些是我在 Controller 中的请求:
@RequestMapping("/posts/new")
public String newPost(Model model){
model.addAttribute("post", new PostForm());
model.addAttribute("categories", categoryRepository.findAll());
return "postForm";
}
@PostMapping
@RequestMapping("post")
public String saveOrUpdate(@ModelAttribute PostForm postForm){
PostForm savedPost = postService.savePostForm(postForm);
return "redirect:/post/show/" + savedPost.getId();
}
有人知道如何制作一个复选框列表以单击然后将类别添加到 Post 实体吗? 谢谢
【问题讨论】:
标签: java html spring spring-boot spring-mvc