Spring Boot + Thymeleaf项目:如何展示服务层返回的错误信息
解决Spring Boot + Thymeleaf无法展示服务层错误信息的问题
我来帮你搞定这个问题!你现在的核心问题是没有把服务层返回的错误信息传递到Model中,也没在前端页面添加对应的渲染逻辑,另外你的Controller里的判断逻辑好像写反了,我一起帮你修正。
第一步:修正Controller逻辑,传递错误信息到前端
首先看你的代码,注释说明是“服务层返回的错误”时返回index页面,但你的判断条件if(StringUtils.isEmpty(loginResponse))意味着只有当服务层返回空字符串时才会回到登录页——这显然和你的需求相反(应该是服务层返回错误信息时才回退)。
修改后的Controller代码如下:
@PostMapping("/home") public String authenticate(@ModelAttribute IndexFormBean indexFormBean, Model model, BindingResult bindingResult) { String loginResponse = userService.login(indexFormBean.getEmail(), indexFormBean.getPassword()); // 当服务层返回非空的错误信息时,回退到登录页并传递错误 if (!StringUtils.isEmpty(loginResponse)) { // 方式1:直接把错误信息放到Model中,供前端直接读取(二选一即可) model.addAttribute("loginError", loginResponse); // 方式2:往BindingResult中添加全局错误,配合Thymeleaf的表单全局错误校验(二选一即可) bindingResult.reject("login_failed", loginResponse); return "index"; } // 登录成功,跳转到home页 return "home"; }
解释一下:
- 把判断条件改成
!StringUtils.isEmpty(loginResponse),确保服务层返回错误信息时才触发回退逻辑 - 提供了两种传递错误的方式,你可以根据自己的习惯选一种使用
第二步:在Thymeleaf页面中渲染错误信息
根据你选的传递方式,在index.html的表单上方或合适位置添加错误展示代码:
如果用方式1(Model直接传值):
<!-- 在表单前添加错误提示框,若使用Bootstrap可直接用alert样式 --> <div th:if="${loginError != null}" class="alert alert-danger mb-3" th:text="${loginError}"></div> <!-- 你的原表单代码 --> <div class="u-expanded-width-xs u-form u-form-1"> <form class="u-clearfix u-form-horizontal u-form-spacing-10 u-inner-form" method="POST" modelAttribute="indexFormBean" name="form" style="padding: 0;" th:action="@{/home}" th:object="${indexFormBean}"> <!-- 原表单内容保持不变 --> </form> </div>
如果用方式2(BindingResult全局错误):
<div th:if="${#fields.hasGlobalErrors()}" class="alert alert-danger mb-3"> <p th:each="error : ${#fields.globalErrors()}" th:text="${error.message}"></p> </div> <!-- 你的原表单代码 -->
额外注意点
- 确保你的
userService.login()方法在登录失败时返回具体的错误信息(比如“邮箱或密码错误”),登录成功时返回null或空字符串,这样Controller的判断逻辑才会生效 - 如果你用了JSR380校验(比如
@Email、@NotBlank),原来的字段级错误展示(比如th:if="${#fields.hasErrors('email')}")依然可以正常工作,和我们添加的全局错误互不冲突
内容的提问来源于stack exchange,提问作者Tokyo
相关产品推荐
相关产品推荐

