我想编辑数据库中现有的数据,通过html格式的字段。但我不能为它创建一个正确的控制器,因为这段代码刚刚创建了一本新书。旧的数据没有改变。
主计长
@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";
}
图书更新
<!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>
1条答案
按热度按时间gab6jxml1#
您的
@PostMapping
缺少路径变量:执行类似以下操作:
顺便说一句,你可以使用
@GetMapping("/books/{id}")
和@PostMapping("/books/{id}")
这样的字符串来使你的URL更好一些。