1

I want to edit exist data from database via html-form with field. But I can not create a right controller for it, because this code just created a new book. Old data was not changed.

Controller

@GetMapping("/bookUpdate/{id}")
public String bookListUpdate(@PathVariable (value = "id") Integer id, Model model, @Valid 
BookDto book) {
    model.addAttribute("book", service.findById(id));
    return "views/bookUpdate";
}

@PostMapping("/edit")
public String editBook(@Valid Book book, @PathVariable (value = "id") Integer id) {
    Book newBook = service.findById(id);
    newBook.setDescription(book.getDescription());
    newBook.setTopic(book.getTopic());
    newBook.setLink(book.getLink());
    service.saveBook(newBook);
    return "views/index";
}

BookUpdate

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
layout:decorate="~{fragments/main_layout}">
<head>
<title>Book Form</title>
</head>
<body>
<div layout:fragment="content" class="container mySpace">

    <form th:action="@{/edit}" th:object="${book}" method="post">
        <div class="form-group">
            <label for="topic" class="form-control-label">Topic</label> <input
                type="text" class="form-control" th:field="*{topic}" id="topic" />
        </div>

        <div class="form-group">
            <label for="description" class="form-control-label">Description</label>
            <textarea class="form-control" th:field="*{description}"
                id="description" style="height: 95px"></textarea>
        </div>

        <div class="form-group">
            <label for="link" class="form-control-label">Link</label><a href=""> <input
                type="text" class="form-control" th:field="*{link}" id="link" />
        </div>

        <input type="submit" value="Submit" class="btn btn-primary" />
    </form>
</div>
</body>
</html>
Anastasia
  • 23
  • 5

1 Answers1

0

Your @PostMapping is missing the path variable:

@PostMapping("/edit")

Do something like:

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

On a side note, you can make your URLs a bit nicer, by using something like @GetMapping("/books/{id}") and @PostMapping("/books/{id}").

Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211
  • Thank you for your answer! But in the result I got page with error 404 (I need to get page "views/index"), and new data were not saved in the database. But I did not get any error in the console. – Anastasia Jul 17 '22 at 11:11
  • Maybe add a new question with more information on your problem. It is unclear to me exactly what is wrong from this comment. – Wim Deblauwe Jul 18 '22 at 06:31