Java 如何在客户端填写列表作为对象字段?
我有实体Java 如何在客户端填写列表作为对象字段?,java,spring,spring-boot,thymeleaf,Java,Spring,Spring Boot,Thymeleaf,我有实体book和author,它们之间存在多对多关系(一本书可以有多个作者,一个作者可以有多本书)。book类有一个私有作者列表字段。我将所有作者的列表作为模型属性传递给视图。视图返回BbookViewModel的对象,其字段是所选作者ID的列表。从选择选项时,如何将此id添加到列表中(使用thymeleaf) BookController @Controller public class BookController { @Autowired private BookRepo
book
和author
,它们之间存在多对多关系(一本书可以有多个作者,一个作者可以有多本书)。book类有一个私有作者列表代码>字段。我将所有作者的列表作为模型属性传递给视图。视图返回BbookViewModel
的对象,其字段是所选作者ID的列表。从选择选项时,如何将此id添加到列表中(使用thymeleaf)
BookController
@Controller
public class BookController {
@Autowired
private BookRepository repository;
@Autowired
private AuthorRepository authorRepository;
@GetMapping("/books")
private String getAllBooks(Model model)
{
// some code ...
model.addAttribute("bookModel", new models.Book());
model.addAttribute("allAuthors", authorRepository.findAll());
return "books.html";
}
@PostMapping(value = "/books/create", produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public ValidationResponse create(@Valid @ModelAttribute models.Book book, BindingResult result)
{
// ...
}
}
books.html的一部分
<form id="bookCreationForm" th:action="@{/books/create}" th:object="${bookModel}"
method="post">
<table class="table">
<tr>
<td><label th:text="Name" /></td>
<td><input type="text" th:field="*{name}" /></td>
</tr>
<tr>
<td><label th:text="Author" /></td>
<td>
<select class="form-control" /*th:field="${}"*/>
<option value="0">Select author</option>
<option th:each="author : ${allAuthors}" th:value="${author.id}" th:text="${author}"></option>
</select>
</td>
</tr>
</table>
</form>
选择作者
我是否应该使用multi-select并将id列表与图书模型分开发送?解决方案很简单:我只需在select
标记中添加一个multiple
属性。绑定系统将在类书籍
中找到作者
字段,并将列表
链接到所选值
<form id="bookCreationForm" th:action="@{/books/create}" th:object="${bookModel}"
method="post">
<table class="table">
<!-- some book fields-->
<tr>
<td><label th:text="Authors" /></td>
<td>
<select class="form-control" name="authors" multiple>
<option th:each="author : ${allAuthors}" th:value="${author.id}" th:text="${author}"></option>
</select>
</td>
</tr>
</table>
</form>
解决方案很简单:我只需在select
标记中添加一个multiple
属性。绑定系统将在类书籍
中找到作者
字段,并将列表
链接到所选值
<form id="bookCreationForm" th:action="@{/books/create}" th:object="${bookModel}"
method="post">
<table class="table">
<!-- some book fields-->
<tr>
<td><label th:text="Authors" /></td>
<td>
<select class="form-control" name="authors" multiple>
<option th:each="author : ${allAuthors}" th:value="${author.id}" th:text="${author}"></option>
</select>
</td>
</tr>
</table>
</form>
查看HTML模板和控制器代码会很有帮助。@Slavivanov已更新。查看HTML模板和控制器代码会很有帮助。@Slavivanov已更新。