SpringBoot RedirectAttributes在百里香中不显示

时间:2020-01-28 02:35:49

标签: spring-boot thymeleaf

控制器代码:

@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,但是它不会在页面上显示;

1 个答案:

答案 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
}