You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot登录页面中显示登录失败的错误提示?

Simplest Way to Show Login Error Message in Spring Boot

Got it, let's get this sorted with the most straightforward approach—since you're working with individual @RequestParam parameters instead of a form-backed entity (which is where BindingResult shines), we can use Spring's Model to pass the error message directly to your login page.

Step 1: Update Your Controller to Send Error Message

Modify your checkLogin method to accept a Model parameter, and add an error attribute when login fails:

@RequestMapping(value = "/loginCheck", method = RequestMethod.POST)
public String checkLogin(@RequestParam String roll, @RequestParam String pass, Model model) {
    if (studentService.existsByRollAndPass(roll, pass)) {
        return "Welcome";
    } else {
        // Add error message to the model
        model.addAttribute("loginError", "Invalid roll number or password. Please try again.");
        return "Login";
    }
}

Step 2: Modify Your HTML to Display the Error

Assuming you're using Thymeleaf (Spring Boot's default templating engine), add a section in your login page to show the error message only when it exists. Place this somewhere above your form (or inside it, wherever makes sense for your UI):

<!-- Error message display -->
<div th:if="${loginError != null}" class="alert alert-danger col-md-8 col-md-offset-2">
    <span th:text="${loginError}"></span>
</div>

<form class="form-horizontal" method="post" action="/loginCheck">
    <!-- Your existing form fields here -->
</form>

If you're using JSP instead of Thymeleaf, replace the Thymeleaf code with JSTL:

<c:if test="${not empty loginError}">
    <div class="alert alert-danger col-md-8 col-md-offset-2">
        ${loginError}
    </div>
</c:if>

Why This Works

Unlike BindingResult (which is for validating form objects annotated with @Valid), this approach directly passes a simple message to the view using Spring's Model—perfect for quick, one-off error cases like login failure. The view then checks if the error attribute exists and renders it only when needed.

内容的提问来源于stack exchange,提问作者Avijit Barua

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:07:57