我正在尝试创建我的第一个 CRUD。 这是我的旅程Site.html 表代码。
<table>
<tr th:each="trip : ${trips}">
<td th:text="${trip.title}"></td>
<td th:text="${trip.destination}"></td>
<td th:text="${trip.id}"></td>
<form th:action="@{/journeys}" th:object="${trip}" method="post">
<input type="hidden" th:field="${trip.id}" />
<button type="submit">Delete</button>
</form>
</tr>
</table>
让我的 Controller 现在看起来像这样。
@RequestMapping(value = {"/journeys"}, method = RequestMethod.GET)
public String journeysPage(Model model){
tripRepository.save(new Trip("Asian Trip", "Asia"));
tripRepository.save(new Trip("European Trip", "Europe"));
tripRepository.save(new Trip("African Trip", "Africa"));
model.addAttribute("trips", tripRepository.findAll());
return "journeysSite";
}
@RequestMapping(value = {"/journeys"}, method = RequestMethod.POST)
public String journeysPageTripDeleting(@RequestParam Long id) {
tripRepository.delete(id);
return "journeysSite";
}
我想要的只是在表中的/journeys 上显示我的所有旅行。在每一行中都有一个删除按钮,该按钮将发布 trip.id,将其从数据库中删除并重定向到完全相同的页面,但删除了 Trip。
但是显然发生了错误:java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'id' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144) ~[spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
有人可以告诉我如何做吗?谢谢。
最佳答案
在您的表单中,您定义了 th:object="${trip}"
对象,这意味着每当提交此表单时都会出现此 trip
对象将作为请求正文发送。
因此,要接收此对象,您必须在 Controller 的方法中接受它。
@RequestMapping(value = {"/journeys/"}, method = RequestMethod.POST)
public String journeysPageTripDeleting(@ModelAttribute Trip trip){
tripRepository.delete(trip.getId());
return "redirect:/journeys";
}
th:field="${id}"
将包含在模型属性提供的对象中,trip
对象将具有您要查找的 ID。
更多关于this .
更新: 根据您当前 Controller 的方法实现,我认为您需要更改的就是这个,
<input type="hidden" th:field="*{id}" /> // No trip.id
关于java - 将对象的变量传递给 thymeleaf 中的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42466933/