Spring - wailidacja

0

Cześć mam taki kalkulator BMR:
Zrobiłem na klasie modelowej walidację jednak problem jest po stronie kontrolera , coś źle piszę , czegoś brakuje... w każdym razie walidacja nie działa
Formularz wygląda tak (plik bmrform)

<form class="list-inline"  th:object="${operationModel}" th:action="@{/bmr}" th:method="post" >
        <div class="form-group" >
            <label class="control-label">Wzrost:</label>
            <input type="text" class="form-control" th:field="*{height}" placeholder="Wzrost w centymetrach"/>
            <p th:if="${#fields.hasErrors('height')}" th:errors="*{height}"/>
        </div>

        <div class="form-group" >
            <label class="control-label">Masa ciała:</label>
            <input type="text" class="form-control" th:field="*{bodyweight}" placeholder="Masa ciała w kg"/>
            <p th:if="${#fields.hasErrors('bodyweight')}" th:errors="*{bodyweight}"/>
        </div>
        <div class="form-group" >
            <label class="control-label">Wiek:</label>
            <input type="text" class="form-control" th:field="*{age}" placeholder="Wiek"/>
            <p th:if="${#fields.hasErrors('age')}" th:errors="*{age}"/>
        </div>

Metody w kontrolerze

 @RequestMapping("/bmr")
    public String createOperationModel(Model model) {
        model.addAttribute("operationModel", new CalculatorFromBmr());
        return "bmrform";
    }

    @RequestMapping(path="/bmr", method = RequestMethod.POST)
    public String add(@ModelAttribute("operationModel") CalculatorFromBmr calculatorFromBmr, Model model) {
        model.addAttribute("result", calculatorBmr.calculate(calculatorFromBmr.getHeight(),calculatorFromBmr.getBodyweight(),calculatorFromBmr.getAge()));
        return "bmrform";
    }

I METODA Z WALIDACJA, W KTÓREJ CZEGOŚ BRAKUJE...

@RequestMapping(value="bmrform", ,method = RequestMethod.POST)
    public String saveResult(@Valid CalculatorFromBmr calculatorFromBmr, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            System.out.println("There were errors");
            bindingResult.getAllErrors().forEach(error -> {
                        System.out.println(error.getObjectName() + " " + error.getDefaultMessage());
                    }
            );
            return "bmrform";
        } else {
            return "redirect:/bmr";
        }

    }
0

Co prawda nie ogarniam tego template engine, ale możesz pokazać jeszcze zawartość CalculatorFromBmr ?

0
@Component
public class CalculatorBmr {

    public double calculate(double height, double bodyweight,int age){
return 66+(13.7*bodyweight)+(5*height)-(6.76*age);
    }

}
0

Chyba podałeś nie tę klasę. W każdym razie myślę że może chodzić o to że masz adnotację @Valid, a w środku nie masz adnotacji walidacyjnych typu @NotBlank, @Length etc.
Jeśli je dodasz to w momencie requestu powinien ci wyskoczyć exception na twarz z błędami walidacji

1 użytkowników online, w tym zalogowanych: 0, gości: 1