0

Hi I am working with spring MVC and thymeleaf and I am not able to update data from my controller as I have following code.The main problem I am facing is that my put method is not getting called.

@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;
    }

and my html page

<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>

any help will be usefull thanks

user7036414
  • 99
  • 3
  • 19

1 Answers1

2

PUT is not a valid argument for method attibute of the form tag. See HTML specification.

Valid methods are GET and POST. And as it's not a REST API, you can use POST method to update.

So just update your mapping from:

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

to

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

And form tag to:

<form action="#" th:action="@{/user/__${user.id}__}/edit" method="post" th:object="${user}">
ledniov
  • 2,302
  • 3
  • 21
  • 27