java - 将对象的变量传递给 thymeleaf 中的 Controller

标签 java spring variables thymeleaf

我正在尝试创建我的第一个 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/

相关文章:

java - 如何从列表中检索特定数据前后的重复数据?

java - 终端流操作,在Java 8中以map作为输入

java - 基于注释的注入(inject);初始化一个空 map

javascript - 如何找到数组中第二好的?

Python:如何防止作用域中的长变量名

java - 使用java home在maven中编译错误

java - 如何将对象转换为 Map 样式 JSON 以通过 Spring 中的 Get 请求发送?

Spring 捕获 index.html 的所有路由

java - Spring 值注入(inject) Map 列表的 Map

python - 如何在Python中重新初始化变量?