首页 > 解决方案 > 当用户使用 Spring Boot 登录失败时,如何在登录页面中显示错误消息?

问题描述

现在我正在用 Spring Boot 做项目。我想在登录失败时显示错误消息。当我做 Maven 项目时,我很容易用 BindingResult 做到了。我按照几个指示完成了我想做的任务。但我无法得到任何适当的解决方案。我需要以最简单的方式提供适当的解决方案。

这是我的Controller

  @RequestMapping(value = "/loginCheck", method = RequestMethod.POST)
    public String checkLogin(@RequestParam String roll, @RequestParam String pass) {
        if (studentService.existsByRollAndPass(roll, pass)) {
            return "Welcome";
        } else {
            return "Login";
        }

我的html文件是

  <form class="form-horizontal" method="post" action="/loginCheck">

        <fieldset>


            <div class="form-group">
                <label class="col-md-4 control-label" for="textinput">Roll</label>
                <div class="col-md-4">
                    <input id="textInput" name="roll" type="text"
                           placeholder="Roll" class="form-control input-md">

                </div>
            </div>
            <!-- Password input-->
            <div class="form-group">
                <label class="col-md-4 control-label" for="password">Password</label>
                <div class="col-md-4">
                    <input id="password" name="pass" type="password"
                           placeholder="password" class="form-control input-md">

                </div>
            </div>
            <!-- Button -->
            <div class="form-group">
                <label class="col-md-4 control-label" for="login"></label>
                <div class="col-md-4">
                    <button id="login" name="login" class="btn btn-primary">Login</button>
                </div>
            </div>

        </fieldset>

    </form>

标签: htmlspringspring-bootthymeleaf

解决方案


您可以在 URL 中添加错误参数,例如 localhost:8080/login?error。然后,在 Thymeleaf 的帮助下,您可以将此 div 添加到 html 中。

<div th:if="${param.error}" class="alert alert-danger">    
    Invalid username and password.
</div>

如果 URL 有错误参数,将显示此 div。

但是,您可能需要更改

return "Login"

return "redirect:Login?error";

推荐阅读