java - 如何在 Spring MVC 中将用户输入与 BigDecimal 对象字段绑定?
问题描述
在我的项目中,我有一个类BigDecimal
作为其领域之一。
@Entity
public class Product {
// ...
@DecimalMin("0.01")
private BigDecimal price;
// ...
}
在百里香中,我有一个表单,其中包含此类字段的输入,负责的price
是:
<form ...>
<input type="number" step="any" th:field="*{price}">
</form>
当@ModelAttribute
从这个表单返回时,price
字段product
为空。它曾经price
在double
. 我怎样才能使这项工作?我想到了一个解决方法 - 将此输入作为 a@RequestParam
然后Product.price
使用double
“手动”值初始化,但是有没有一些解决方案可以让百里香为我做到这一点?
解决方案
那应该行得通。我刚刚使用 Spring Boot 2.3.0 进行了如下测试:
我正在使用表单数据对象,因为直接将您的实体用于表单会使存储库过于混乱 IMO:
import javax.validation.constraints.DecimalMin;
import java.math.BigDecimal;
public class ProductFormData {
@DecimalMin("0.01")
private BigDecimal price;
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
}
使用这样的控制器:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/product")
public class ProductController {
@GetMapping
public String product(Model model) {
model.addAttribute("product", new ProductFormData());
return "product";
}
@PostMapping
public String doSaveProduct(@ModelAttribute("product") ProductFormData formData) {
System.out.println("formData = " + formData.getPrice());
return "redirect:/product";
}
}
和这样的product.html
模板:
<!DOCTYPE html>
<html lang="en" xmlns:th="http:www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Product</title>
</head>
<body>
<h1>Product</h1>
<form th:action="@{/product}" th:object="${product}" method="post">
<input type="number" step="any" th:field="*{price}">
<button type="submit">submit</button>
</form>
</body>
</html>
当我在表单中输入一个数字并按“提交”时,我会在控制台中看到打印的值。
推荐阅读
- angular - 即使选择了取消或关闭,离子模式也会记住复选框选择
- javascript - 在 JavaScript 检测是否缺少某些图像之前等待所有图像以 HTML 错误加载
- c# - 当 transform.parent 设置为 null 时游戏对象放大
- dictionary - XSLT 以数组作为基于 csv 文件的值构建映射
- c - 并发:使用 pthread_mutex 原子化增量操作
- laravel - laravel 5.7 关系属于hasmany错误
- javascript - 我无法让多个 2d 对象从画布 x 和 y 反弹
- r - 在使用 cor 函数测试 R 中的显着性后确定 P 值
- arrays - 搜索路径数组以删除包含字符串的文件夹 - 批处理
- android - 在导航抽屉中单击后片段没有被替换