从列表中取出对象并传递给另一个方法

时间:2016-06-22 16:38:38

标签: spring-mvc thymeleaf

正如标题所描述的那样,使用百里香,我会显示列表的内容,然后在列表中的每个项目旁边放置“更新”按钮,将特定对象发送到编辑表单页面。

以下是将列表添加到列表视图的控制器方法:

@RequestMapping("/list")
    public String list(Model model){
        List<Employee> employees = repository.findAll();
        model.addAttribute("employees", employees);
        return "list";
    }

以下是thymeleaf html代码:

<tr th:each="emp : ${employees}">
            <td th:text="${emp.id}"></td>
            <td th:text="${emp.name}"></td>
            <td th:text="${emp.surname}"></td>
            <td th:text="${emp.age}"></td>
            <td th:text="${emp.department}"></td>
            <td>
                <form th:action="@{/update}" method = "POST" th:object="${emp}">
                    <input type="hidden" th:field="*{id}"></input>
                    <input type="hidden" th:field="*{name}" ></input>
                    <input type="hidden" th:field="*{surname}"></input>
                    <input type="hidden" th:field="*{age}"></input>
                    <input type="hidden" th:field="*{department}"></input>
                    <button type = "submit">Update</button>
                </form>
            </td>
</tr>

这是接收方法:

@RequestMapping("/update")
    public String update(@ModelAttribute("emp") Employee emp){

        return "update";
    }

我一直收到以下异常:

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'emp' available as request attribute

如果您对完成此任务有任何想法,请与我们联系。

1 个答案:

答案 0 :(得分:0)

这可能会有所帮助。像这样改变你的控制器。它适合我。

model.addAttribute("emp", new Employee());

@RequestMapping("/list")
    public String list(Model model){
        List<Employee> employees = repository.findAll();
        model.addAttribute("emp", new Employee());
        model.addAttribute("employees", employees);
        return "list";
    }