0

I'm trying to validate one of the parameters on a get request and would like to add an error message to the view and then return the same view with the added error message when validation fails. I've spent a lot of time reading documentation and looking at examples but haven't been able to figure out how it works with Spring MVC and Thymeleaf in their current versions.

The method in question:

    @GetMapping(value = "/converter", params = {"from", "to", "amount"})
    public String convert(@RequestParam("from") String from,
                          @RequestParam("to") String to,
                          @RequestParam("amount") @Valid @NotBlank @DecimalMin("0.0") double amount,
                          Model model) {
        String conversion = converterService.convert(new ConversionDTO(from, to, amount));
        //model.addValidationErrorsToModelSomehow(errors);
        model.addAttribute("conversion", conversion);
        return "main";
    }

The view:

<div>
    <!-- display error here -->
    <p th:text="${'Has error: ' + error}"></p>
    <form method="get">
        Amount
        <input type="text" name="amount">
        From
        <select name="from">
            <option value="SEK">SEK</option>
            <option value="EUR">EUR</option>
            <option value="CHF">CHF</option>
            <option value="USD">USD</option>
        </select>
        To
        <select name="to">
            <option value="SEK">SEK</option>
            <option value="EUR">EUR</option>
            <option value="CHF">CHF</option>
            <option value="USD">USD</option>
        </select>
        <input type="submit">
        <input type="text" th:value="${conversion}">
    </form>
</div>

What do I need to add to get it working?

Rookierookie
  • 167
  • 1
  • 1
  • 11
  • Could you please check : [Spring MVC thymleaf error display](https://stackoverflow.com/questions/22948257/thymeleaf-not-displaying-spring-form-error-messages) – Deepak Dec 17 '19 at 10:38
  • I've already tried using a BindingResult object, apparently this does not work with @RequestParam annotations as I understand it... – Rookierookie Dec 17 '19 at 10:44
  • May be you need to bind it with thymleaf ` ` . Please check https://www.baeldung.com/spring-thymeleaf-request-parameters – Deepak Dec 17 '19 at 10:57
  • thanks, but that doesn't cover passing errors generated by validation annotations to the view. I'm aware of how to use the Model object, I just can't figure out how to capture the errors generated by the annotations on my `amount` RequestParameter... – Rookierookie Dec 17 '19 at 11:05
  • I am not very much sure about the way you are trying to display errors . Meanwhile open developer tools and check on firing get request in response you are actually getting errors from backend . – Deepak Dec 17 '19 at 11:09

0 Answers0