控制器代码:
@Controller
@RequestMapping("/admin")
@AllArgsConstructor
public class AdminController {
private AdminUserService adminUserService;
@PostMapping("/login")
public String login(@RequestParam String username, @RequestParam String password, @RequestParam String kaptcha, RedirectAttributes attributes, HttpSession session) {
String errorMsg;
if (StringUtils.isEmpty(kaptcha)) {
errorMsg = "kaptcha can't be empty";
attributes.addFlashAttribute("errorMsg", errorMsg);
return "redirect:admin/login";
}
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
errorMsg = "username or password can't be empty";
attributes.addFlashAttribute("errorMsg", errorMsg);
return "redirect:admin/login";
}
String code = (String) session.getAttribute(Const.kapchaCode);
if (StringUtils.isEmpty(code) || !kaptcha.equals(code)) {
errorMsg = "invalid kaptcha code";
attributes.addFlashAttribute("errorMsg", errorMsg);
return "redirect:admin/login";
}
AdminUser login = adminUserService.login(username, password);
if (login == null) {
errorMsg = "invalid username password combination";
attributes.addFlashAttribute("errorMsg", errorMsg);
return "redirect:admin/login";
}
session.setAttribute("loginUser", login.getAlias());
session.setAttribute("loginUserId", login.getAdminUserId());
return "redirect:/admin/index";
}
模板:
<div class="form-group">
<div th:if="${errorMsg}" class="alert alert-danger" th:text="${errorMsg}"></div>
</div>
出现错误时,不会显示errorMsg。 我已经检查过errorMsg确实进入了RedirectAttributes,但是它不会在页面上显示;
答案 0 :(得分:0)
请在重定向控制器admin/login
中设置值。例子
@RequestMapping(value = "admin/login", method = RequestMethod.GET)
public String OtherController(@ModelAttribute("errorMsg") String errorMsg, Model model) {
model.addAttribute("errorMsg", errorMsg);
return "login";//template name
}