首页 > 解决方案 > 如何在 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为空。它曾经pricedouble. 我怎样才能使这项工作?我想到了一个解决方法 - 将此输入作为 a@RequestParam然后Product.price使用double“手动”值初始化,但是有没有一些解决方案可以让百里香为我做到这一点?

标签: javaspringspring-mvcthymeleaf

解决方案


那应该行得通。我刚刚使用 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>

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


推荐阅读