我有一个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
答案 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
;
答案 1 :(得分:-2)
不应该是
字段=&#34; * {进价}&#34;
相反它应该是
个:字段=&#34; $ {进价}&#34;