Ad

Thymeleaf / SpringBoot : Failed To Convert Property Value Of Type Java.lang.String To Required Type Float For Property

- 1 answer

I have a Thymeleaf template

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

mapped to this property:

private float purchasePrice;

But I have this error:

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"

I've trie also with

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"

I also tried with <input type="text" th:field="${purchasePrice}" .../>

but the I got this error

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

Answer

I suppose your private float purchasePrice; is defined in a simple POJO class. Let's say the POJO is named Price:

public class Price {
    
    private float purchasePrice;

    public float getPurchasePrice() {
        return purchasePrice;
    }

    public void setPurchasePrice(float purchasePrice) {
        this.purchasePrice = purchasePrice;
    }
}

To make *{purchasePrice} visible in the view you should first add Price to a modelAttribute in your Controller class:

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

The HTML form looks simple as:

<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>

You see that I add a new field called th:object="${price}".

Command object is the name Spring MVC gives to form-backing beans, this is, to objects that model a form’s fields and provide getter and setter methods that will be used by the framework for establishing and obtaining the values input by the user at the browser side.

The mapping for the post request is looks like the following:

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

So if I send the value 0.132872 its converted to the object Price and holds the value purchasePrice = 0.132872;

enter image description here

Ad
source: stackoverflow.com
Ad