I have a form to handle password change.
<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>
In the controller
@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";
}
when the user clicks send if the error and returns but the form data is lost as shown:
Is there any way for user data to be entered without being lost but still preserved? Thank you
I changed the View to following code and it worked.
<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>
my controller code for skipping all other logic and do a simple redirect.
@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";
}