在Spring Boot中提交时如何将数据保留在表单上以及如何使其无效

时间:2019-05-02 02:41:46

标签: spring spring-boot thymeleaf bean-validation

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

<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";
}

当用户单击“发送”(如果错误并返回),但表单数据丢失时,如下所示: enter image description here

有什么方法可以输入用户数据而不会丢失但仍然保留?谢谢

1 个答案:

答案 0 :(得分:1)

我将“视图”更改为以下代码,并且可以正常工作。

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

    }