The project is developed with Spring Boot 3.1.7 with Spring Web and Thymeleaf. I cannot find an explanation to the fact that Spring uses the value of a @Pathvariable, specifically an id, to assign the value of the id attribute of an object which comes from the request body.
There is a form mapped on an object of custom type Book which has several attributes and an Integer id. The id is not inside the form, but is used to compose the post action.
<form
id="edit-book"
method="post"
th:object="${book}"
th:action="@{/books/edit/{id}(id=${book.id})}"
>
<label for="title">Title</label>
<input type="text" id="title" th:field="*{title}">
// other inputs
</form>
After submit, the http request body doesn't contain the id attribute, but the Book object parameter (formBook) has it automatically populated.
I think it happens because Spring assumes that the @Pathvariable Integer id is the id of the next object passed as parameter. Is there a more detailed explanation?
Another thing I cannot explain is that inside the return statement, the placeholder {id} inside the redirect is automatically populated with the same id value as well... I thought the only way you could add a path variable to a redirect was by concatenating (i.e. return "redirect:/books/show/" + formBook.getId();) but it works the way you see in the next code
@PostMapping("/edit/{id}")
public String update(@PathVariable Integer id, @Valid @ModelAttribute("book") Book formBook,
BindingResult bindingResult) {
// ... handle validation
Book savedBook = bookRepository.save(formBook);
return "redirect:/books/show/{id}";
}
}