【问题标题】:Thymeleaf / SpringBoot : Failed to convert property value of type java.lang.String to required type float for propertyThymeleaf / SpringBoot:无法将 java.lang.String 类型的属性值转换为属性所需的浮点类型
【发布时间】:2018-02-18 15:45:31
【问题描述】:

我有一个 Thymeleaf 模板

<input type="text"    th:field="*{purchasePrice}" ../>

映射到这个属性:

private float purchasePrice;

但我有这个错误:

Failed to convert property value of type java.lang.String to required type float for property purchasePrice; nested exception is java.lang.NumberFormatException: For input string: "0,132872"

我也试过

Failed to convert property value of type java.lang.String to required type float for property purchasePrice; nested exception is java.lang.NumberFormatException: For input string: "0.132872"

我也试过&lt;input type="text" th:field="${purchasePrice}" .../&gt;

但是我收到了这个错误

 java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'purchasePrice' available as request attribute

【问题讨论】:

    标签: spring spring-mvc spring-boot thymeleaf


    【解决方案1】:

    我想你的private float purchasePrice; 是在一个简单的 POJO 类中定义的。假设 POJO 被命名为Price

    public class Price {
        
        private float purchasePrice;
    
        public float getPurchasePrice() {
            return purchasePrice;
        }
    
        public void setPurchasePrice(float purchasePrice) {
            this.purchasePrice = purchasePrice;
        }
    }
    

    要使 *{purchasePrice} 在视图中可见,您应该首先将 Price 添加到 Controller 类中的 modelAttribute:

     @GetMapping("/")
     public String index(Model model) {
         model.addAttribute("price", new Price());
         return "index";
     }
    

    HTML 表单看起来很简单:

    <form method="POST" th:action="@{/price}" th:object="${price}">
        <input type="text" th:field="*{purchasePrice}" />
        <button type="submit" name="submit" value="value" class="link-button">This
            is a link that sends a POST request</button>
    </form>
    

    您看到我添加了一个名为th:object="${price}" 的新字段。

    Command 对象是 Spring MVC 赋予表单支持 bean 的名称, 这就是对表单字段建模并提供 getter 和 框架将使用的 setter 方法来建立和 获取用户在浏览器端输入的值。

    post 请求的映射如下所示:

    @PostMapping("/price")
    public String index(@ModelAttribute Price price) {
        return "index";
    }
    

    因此,如果我发送值 0.132872 其转换为对象 Price 并保存值 purchasePrice = 0.132872;

    【讨论】:

      【解决方案2】:

      不应该是

      field="*{purchasePrice}"

      应该是这样的

      th:field="${purchasePrice}"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-13
        • 2017-05-06
        • 2015-03-29
        • 2013-10-26
        • 2021-06-26
        • 2019-07-11
        • 1970-01-01
        相关资源
        最近更新 更多