Home > Net >  Edit data in the database
Edit data in the database

Time:07-18

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

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

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

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

        <input type="submit" value="Submit"  />
    </form>
</div>
</body>
</html>

CodePudding user response:

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}").

  • Related