通过Spring Boot将选中的值从复选框列表中获取到控制器
我使用SpringBoot和Thymeleaf作为查看器,我想从表中删除所有选定的项。因此,我需要向控制器传递一个列表,其中包含所选复选框中的值 这是我对控制器的方法:通过Spring Boot将选中的值从复选框列表中获取到控制器,spring,spring-mvc,checkbox,spring-boot,thymeleaf,Spring,Spring Mvc,Checkbox,Spring Boot,Thymeleaf,我使用SpringBoot和Thymeleaf作为查看器,我想从表中删除所有选定的项。因此,我需要向控制器传递一个列表,其中包含所选复选框中的值 这是我对控制器的方法: @PostMapping("/admin/rates/prices/delete") public String delete(@ModelAttribute Rate price, ServletWebRequest request){ if(request.getParameterValues("idChecked
@PostMapping("/admin/rates/prices/delete")
public String delete(@ModelAttribute Rate price, ServletWebRequest request){
if(request.getParameterValues("idChecked") != null){
for(String idCheckedStr : request.getParameterValues("idChecked")){
int idrate = Integer.getInteger(idCheckedStr);
rateRepository.deleteRate(idrate);
}
}
return "redirect:/admin/rates/prices";
}
我得到一个空指针异常:
java.lang.NullPointerException: null
at com.rentalwebs.controllers.rates.PriceListController.delete(PriceListController.java:42)
我认为此方法应收集以下值:
request.getParameterValues("idChecked")
这是表单上的一行,它创建了带有Thymeleaf注释的每个复选框:
<input type="checkbox" th:name="idChecked" th:value="${price.idrate}"/>
这是表单的视图代码:
<form th:action='@{/admin/rates/prices/delete}'
method="POST"
th:object="${rate}">
<button type="submit" name='delete' value="delete"
class='btn btn-secondary btn-sm'
th:text="#{delete}"
data-toggle="tooltip" data-placement="right"
th:title="#{delete.selected}">
</button>
<p></p>
<table class='table table-sm responsive'>
<thead class='thead-default'>
<tr>
<th><input type="checkbox" id="checkAll"/></th>
<th th:text='#{from}'></th>
<th th:text='#{to}'></th>
<th th:text='#{price}'></th>
</tr>
</thead>
<tbody>
<tr th:each="price : ${prices}">
<td>
<input type="checkbox" th:name="idChecked" th:value="${price.idrate}"/>
</td>
<td th:text="${#temporals.format(price.datefrom, 'dd/MM/yyyy')}"></td>
<td th:text="${#temporals.format(price.dateto, 'dd/MM/yyyy')}"></td>
<td th:text="${price.price} + ' €'"></td>
</tr>
</tbody>
</table>
</form>
提前感谢您的帮助:-这是解决方案的代码,摘自以下评论:
@PostMapping("/admin/rates/prices")
public String delete(@RequestParam("idChecked") List<String> idrates){
if(idrates != null){
for(String idrateStr : idrates){
int idrate = Integer.parseInt(idrateStr);
rateRepository.deleteRate(idrate);
}
}
return "redirect:/admin/rates/prices";
}
是,ServletWebRequest将获取所有参数。但是,不要使用它。使用更多的Spring惯用方法。通过@RequestParamidChecked列表ID获取参数值列表。然而,NPE发生在哪里?在控制器的第42行调用什么方法?使用完整堆栈跟踪更新您的问题。我建议您查找Integer.getIntegerString s的功能。它不会解析字符串并为您提供123->123的int表示形式。这很可能是导致NullPointerException的原因,因为getInteger将在此处返回null,如果取消对null的整数的装箱,则会得到NullPointerException。如果要将字符串解析为有符号十进制整数,请使用integer.parseIntString s,并注意,如果尝试解析包含非数字字符的字符串,仍可能存在异常NumberFormatException。非常感谢@BranislavLazic和@TommySchmidt,我用@RequestParam而不是ServletWebRequest解决了这个问题,并用Integer.parseIntString s将字符串转换成int。