繁体   English   中英

如何在 Spring MVC 中将用户输入与 BigDecimal 对象字段绑定?

[英]How to bind user input with a BigDecimal object field in Spring MVC?

在我的项目中,我有一个类,其中BigDecimal作为其字段之一。

@Entity
public class Product {

    // ...
   
    @DecimalMin("0.01")
    private BigDecimal price;

    // ...
}

thymeleaf 中,我有一个包含此类字段输入的表单,负责price的表单是:

<form ...>
   <input type="number" step="any" th:field="*{price}">
</form>

此表单返回@ModelAttributeproductprice字段为空。 它曾经在price double时起作用。 我怎样才能使这项工作? 我想到了一个解决方法 - 将此输入作为@RequestParam然后使用double值“手动”初始化Product.price但是否有一些解决方案,以便 thymeleaf 为我做到这一点?

那应该工作。 我刚刚使用 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>

当我在表单中输入一个数字并按“提交”时,我会在控制台中看到打印的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM