【发布时间】:2025-11-26 11:45:01
【问题描述】:
我只是在自学 Spring 框架,并试图制作一个简单的库应用程序,它将用户(书籍)输入以表单形式存储在 H2 数据库中,然后向用户显示来自 H2 数据库的新输入数据。
表单提交尝试1:
我现在有一个有效的 POST 方法,可以正确地将一本新书保存到 H2 存储库 - 但是当我尝试将此方法连接到提交表单时,不会发生这样的存储库存储。
表单提交尝试2:
使用 POSTman 3 处理 POST 请求:
使用 POSTman 4 处理 POST 请求:
代码 sn-ps 如下:
内含 Thymeleaf 表单的 HTML 文件:
<h2> Enter a book below to add it to your basket: </h2>
<form action="/addToBasket" th:action="@{/addToBasket}" th:object="${book}" method="post">
<p> Book Title: <input type="text" th:field="*{bookTitle}"></p>
<p> Author: <input type="text" th:field="*{bookAuthor}"></p>
<p> publicationYear: <input type="text" th:field="*{publicationYear}"></p>
<p> price: <input type="text" th:field="*{price}"></p>
<br>
<!-- <input type="submit" value="Submit">-->
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
控制器类中的 POST 方法适用于来自 POSTman 的 POST 请求,但无法以相同的方式存储表单数据:
@PostMapping("/addToBasket")
public Basket addToBasket(@RequestBody Basket newBook) {
return basketRepository.save(newBook);
}
篮子@实体:
@Entity
public class Basket {
private @Id @GeneratedValue Long basketId;
private String bookTitle;
private String author;
private String publisher;
public Basket() {
}
public Basket( String bookTitle, String author, String publisher) {
this.bookTitle = bookTitle;
this.author = author;
this.publisher = publisher;
}
【问题讨论】:
-
与您使用 Postman 的尝试不同,从浏览器发布表单不使用 JSON。 spring.io/guides/gs/handling-form-submission 可能会有所帮助。
-
谢谢@AndyWilkinson 到目前为止,我实际上一直在使用本指南,但我对从浏览器发布表单实际使用的内容以及如何获取发布表单的属性并将它们保存到存储库感到困惑(作为一本书)。你知道这是如何实现的吗?
-
别担心,安迪,我刚刚破解了它 :)
标签: java spring spring-boot thymeleaf h2