Thymeleaf / SpringBoot:无法将类型为java.lang.String的属性值转换为属性所需的float类型

时间:2018-02-18 15:45:31

标签: spring spring-mvc spring-boot thymeleaf

我有一个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"

我也试过了<input type="text" th:field="${purchasePrice}" .../>

但是我收到了这个错误

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

2 个答案:

答案 0 :(得分:0)

我想你的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},您应首先将Pirce添加到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方法将由框架用于建立和   获取用户在浏览器端输入的值。

发布请求的映射如下所示:

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

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

enter image description here

答案 1 :(得分:-2)

不应该是

字段=&#34; * {进价}&#34;

相反它应该是

个:字段=&#34; $ {进价}&#34;