Search code examples
javaspring-bootspring-mvchttp-status-code-404

The Edit button in my spring boot api does not work. An unexpected error has occurred (type=Not found, status=404)


I have two methods for the button in my MainController:

@GetMapping("/edit/{id}")
    public String editUser(@PathVariable(name = "id") Long id, Model model){
        model.addAttribute("userEntity", userService.findById(id));
        return "edit";
    }
    @PutMapping("/edit/{id}")
    public UserEntity editUser(@PathVariable(name = "id") Long id) {
        return userService.updateUser(id);
    }

Update method in my UserService:

public UserEntity updateUser(@RequestParam Long id) {
        UserEntity userEntity = userRepo.findById(id).get();
        userEntity.setName(userEntity.getName());
        userEntity.setPassword(userEntity.getPassword());
        return userRepo.save(userEntity);
    }

edit.html file:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Edit</title>
</head>
<body>
<form th:action="@{/edit}" method="post" th:object="${userEntity}">
    <div><label> New username : <input th:field="*{name}" type="text" name="username"/> </label></div>
    <div><label> New password: <input th:field="*{password}" type="password" name="password"/> </label></div>
    <div><input type="submit" value="Save"></div>
</form>
<a href="/">Return to main page</a>
</body>
</html>

I can not understand in any way why the Whitelabel Error Page error occurs, it does not display an error in the console. On the page he writes There was an unexpected error (type=Not Found, status=404).

I tried to watch the guides (I'm new to Spring), but everyone has Update methods written differently. And I'm also not sure about @PostMapping, whether it needs to be added to the MainController or not, if necessary, how


Solution

  • You need to use @PostMapping if you submit a HTML form. Because it doesn't support a method PUT. However, you can use Postman to make a PUT request. The POST method is used to submit a new user, because it has not yet id. If you want update an existing user, then you should add id to the form.

    @PostMapping("/update")
        public UserEntity updateUser(@RequestParam("id") Long id) {
            return userService.updateUser(id);
        }
    

    The html form

    <form th:action="@{/update}" method="post" th:object="${userEntity}">
        <div><label> New username : <input th:field="*{name}" type="text" name="username"/> </label></div>
        <div><label> New password: <input th:field="*{password}" type="password" name="password"/> </label></div>
        <div><input type="submit" value="Save"></div>
        <input th:field="*{id}" type="hidden" name="id"/>
    </form>