java - 使用 Spring + Thymeleaf 从表中的选定复选框中获取 Id
问题描述
我收到一个错误 NotReadablePropertyException: Invalid property 'userIds' of bean class [...ListOfIds]... 我不知道为什么。如果我删除th:field
复选框上的属性,表格会正确填写。我已经尝试过th:field="*{requestIds}"
,th:field="*{requestIds.ids}"
我正在尝试做的是从选定的复选框中收集 id 列表并将它们传递回控制器以进行发布。
形式
public class ListOfIds {
List<Long> ids = new ArrayList<>();
public List<Long> getIds() { return ids; }
// I've tried both set methods by themselves and together.
public void setIds(List<Long> ids) { this.ids = ids; }
public void setIds(Long[] ids) { this.ids = Arrays.asList(ids); }
}
请求 bean
public class Request {
long id;
String name;
String phone;
String email;
// Getters/Setters
}
控制器
@GetMapping("/myTable")
public ModelAndView getMyTable(ModelAndView mav) {
mav.setViewName("myTable");
List<Request> requests = service.getRequests();
mav.addObject("requests", requests);
mav.addObject("requestIds", new ListOfIds());
return mav;
}
@PostMapping("/myTable")
public ModelAndView postRequests(ModelAndView mav, @ModelAttribute("requestIds") ListOfIds ids) {
...
}
html页面
...
<form method="post" th:action="@{/myTable}" th:object="${requestIds}">
<table class="table ...">
<thead>
<tr>
<th><input type="checkbox" class="selectall" data-target="requests-all"/></th>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr role="row" th:each="request : ${requests}">
<td>
<input type="checkbox" name="requestId" data-target="requests-all"
th:value="${request.id}" th:field="*{requestIds}"/>
</td>
<td th:text="${request.name}"></td>
<td th:text="${request.phone}"></td>
<td th:text="${request.email}"></td>
</tr>
</tbody>
</table>
<button class="btn btn-primary show-selected">Process</button>
</form>
...
<script>
$(document).ready(function() {
$('button').click(function(e) {
if !(confirm("Are you sure you wish to process these requests")) {
e.preventDefault();
}
});
});
</script>
...
解决方案
所以答案是,name
不要th:field
一起玩好。
我进行了以下更改并且有效:
控制器
@PostMapping("/myTable")
public ModelAndView postRequests(ModelAndView mav,
@ModelAttribute("requestIds") Long[] ids) {
...
}
html
<form id="postMyTable" method="post" th:action="@{/myTable}">
<table ...
<input type="checkbox" name="requestId" data-target="requests-all"
th:value="${request.id}"/>
...
<script>
$(document).ready(function() {
$('button').click(function(e) {
if !(confirm("Are you sure you wish to process these requests")) {
e.preventDefault();
} else {
$("#postMyTable").submit();
}
});
});
</script>
推荐阅读
- angular - Angular Material:如何通过仅单击复选框来选择表格行?
- python - 将 CSV 标头与 MySQL 模式列匹配
- java - textview的SQLite android数据库错误
- python - 有时 Python 代码仅在 CMD 中按下 CTRL+C 时才会停止和启动
- python - 如何在 Anaconda Navigator 中下载 opencv-python 库?
- c# - 如何模拟物理键盘输入
- html - 边距顶部导致父 div 下降
- vue.js - Vuetify - 限制滑块可以在 v-slider 中移动到的最小值
- java - 在数组中查找以特定数字开头的数字
- java - 如何从可运行的可调用对象中获取类名