spring + thymeleaf无法更新

时间:2017-07-03 11:48:13

标签: spring-mvc thymeleaf

您好我正在使用spring MVC和thymeleaf,我无法更新控制器中的数据,因为我有以下代码。我面临的主要问题是我的put方法没有被调用。< / p>

@GetMapping("/{id}/edit")
    public String editUser(@PathVariable("id") int id, Model model) {
        logger.info("++++++++++++[edit User]\n\n" + userService.findById(id));
        model.addAttribute("user", userService.findById(id));
        return "user/edit";
    }

    @PutMapping("/{id}/edit")
    public String updateUser(@PathVariable("id") int id, @ModelAttribute("user") User user, Model model) {
        logger.info("\n\n+++++++++++++++++inside Update");
        User toUpdate = userService.findById(user.getId());
        user.setUserName(user.getUserName() != null ? user.getUserName() : toUpdate.getUserName());
        user.setName(user.getName() != null ? user.getName() : toUpdate.getName());

        logger.info(user.toString());
        userService.updateUser(user);
        model.addAttribute("user", userService.findById(user.getId()));
        return "redirect:/user/" + id;
    }

和我的html页面

<form action="#" th:action="@{/user/__${user.id}__}" method="put"
                    th:object="${user}">
                    <div class="form-group">
                        <label for="txtUserName">User-name</label> <input
                            class="form-control" id="txtUserName" placeholder="User Name"
                            th:feild="${user.userName}" />
                    </div>
                    <div class="form-group">
                        <label for="txtName">First Name</label> <input
                            class="form-control" id="txtName" placeholder="Full Name"
                            th:feild="${user.name}" />
                    </div>
                    <div class="form-group">
                        <label for="calDob">Date of Birth</label> <input
                            class="form-control" id="calDob" placeholder="dd/MM/yyyy" />
                    </div>

                    <button type="submit" th:method="put" class="btn btn-success">Update</button>
                    <a href="#" th:href="@{/user/__${user.id}__}"
                        class="btn btn-primary">Cancel</a> <a th:method="delete"
                        href="javascript:deleteUser('${user.id}');" class="btn btn-danger">Delete</a>
                </form>

任何帮助都会有用,谢谢

1 个答案:

答案 0 :(得分:1)

PUT不是method标记form的有效参数。请参阅HTML specification

有效方法为GETPOST。由于它不是REST API,您可以使用POST方法进行更新。

所以只需从以下位置更新您的映射:

@PutMapping("/{id}/edit")

@PostMapping("/{id}/edit")

将表格标记为:

<form action="#" th:action="@{/user/__${user.id}__}/edit" method="post" th:object="${user}">