如何在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

