我正在尝试为网站编写密码重置功能。我遇到了一个问题,我正在使用几个重定向从后映射过渡到getmapping,它们似乎并没有随身携带所需的属性,即我试图重置密码形式的用户对象。是我的一个映射示例:
@PostMapping("/user/forgot")
public String emailCheck (@RequestParam String email, Model model){
User user = userDao.findByEmail(email);
if (user==null){
model.addAttribute("wrongEmail", true);
return "redirect:/user/forgot";
}
else {
model.addAttribute("user", user);
return "redirect:/verifysecurity";
}
}
这是模板,然后在其中调用用户属性:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head th:replace="fragments/header :: header('Security', '')"></head>
<body>
<div th:replace="fragments/navbar :: navbar"></div>
<h1 th:if="${wrongAnswer}">Answer does not match record on file, please try again</h1>
<h1>Please answer your security question: WHat is your best friends name?</h1>
<form id="passwordForm" th:action="@{/verifysecurity}" th:method="post">
<label for="answer">Answer</label>
<br/>
<input type="text" id="answer" name="answer"/>
<input type="hidden" name="user" id="user" th:value="${user}"/>
<input type="submit" class="btn btn-block btn-primary" value="Request"/>
</form>
</body>
</html>
然后在下一个映射中,我为用户得到一个空指针异常:
@PostMapping("/verifysecurity")
public String verify (Model model, @RequestParam User user, @RequestParam String answer){
String security = user.getSecurity_question();
if (answer.equals(security)){
model.addAttribute("user", user);
return "redirect:/reset/password";
} else {
model.addAttribute("wrongAnswer", true);
model.addAttribute("user", user);
return "redirect:/verifysecurity";
}
}
该如何解决?如果模型属性不起作用,我应该怎么做?
答案 0 :(得分:2)
使用spring RedirectAttributes.addFlashAttribute()
,顾名思义,它存储在flashmap中,内部使用用户会话将该数据传递给下一个重定向,并删除使用的数据。
@RequestMapping(value = "/accounts", method = RequestMethod.POST)
public String handle(Account account, BindingResult result, RedirectAttributes redirectAttrs) {
// Save account ...
redirectAttrs.addFlashAttribute("message", "Account created!");
return "redirect:/accounts/{id}";
}