spring boot 提交无效时如何保留表单数据

How to keep the data on the form when submitted and invalid in spring boot

我有一个表格来处理密码更改。

<form method="POST" th:object="${changePassword}" th:action="@{/user/change_pass}">
    <input type="password" class="form-control" id="oldpass" th:field="*{oldPassword}">
    <input type="password" class="form-control" id="newpass" th:field="*{newPassword}"
    <input type="password" class="form-control" id="confirmPass" th:field="* {confirmNewPassword}"
    <input type="submit" class="btn btn-outline-primary btn-rounded waves-effect" value="Send"/>
</form>

在控制器中

@GetMapping(value = "/user/change_pass")
private String changePasswordPage(Model model){

    if (!model.containsAttribute("changePassword")) {
        model.addAttribute("changePassword", new ChangePassword());
    }

    return "web/view/accPasswordPage";
}

@PostMapping(value = "/user/change_pass")
private String saveNewPassword(@Valid ChangePassword changePassword, BindingResult result, Model model, RedirectAttributes redirectAttributes){
    if (result.hasErrors()) {
        redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.changePassword", result);
        redirectAttributes.addFlashAttribute("changePassword", changePassword);
        return "redirect:/user/change_pass";
    }
    return "redirect:/user/home";
}

当用户点击发送时如果报错returns但是表单数据丢失如图:

有没有什么办法可以让用户数据录入不丢失又保留下来?谢谢

我将视图更改为以下代码并且有效。

<form method="POST" th:object="${changePassword}" th:action="@{/user/change_pass}">
    <input type="password" class="form-control" id="oldPassword" name="oldPassword" th:value="*{oldPassword}">
    <input type="password" class="form-control" id="newPassword" name="newPassword" th:value="*{newPassword}" />
    <input type="password" class="form-control" id="confirmNewPassword" name="confirmNewPassword" th:value="*{confirmNewPassword}" />
    <input type="submit" class="btn btn-outline-primary btn-rounded waves-effect" value="Send"/>
</form>

我的控制器代码用于跳过所有其他逻辑并进行简单的重定向。

@GetMapping(value = "/user/change_pass")
    private String changePasswordPage(Model model){

        if (!model.containsAttribute("changePassword")) {
            model.addAttribute("changePassword", new ChangePassword());
        }

        return "index";
    }

    @PostMapping(value = "/user/change_pass")
    private String saveNewPassword(@Valid ChangePassword changePassword, BindingResult result, Model model, RedirectAttributes redirectAttributes){
            redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.changePassword", result);
            redirectAttributes.addFlashAttribute("changePassword", changePassword);
            return "redirect:/user/change_pass";

    }