gpt4 book ai didi

spring-boot - Thymeleaf 和 Spring 引导中的错误处理

转载 作者:行者123 更新时间:2023-12-05 04:59:04 25 4
gpt4 key购买 nike

在我的 spring boot thymeleaf 应用程序中,我正在努力弄清楚如何将服务层返回的错误消息显示到 UI 上。

我的 UI 代码 (index.html) 是

<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}">
<div class="u-form-group u-form-name u-form-group-1">
<label for="email-dbf3"
class="u-form-control-hidden u-label">Email</label>
<input type="email" placeholder="Enter a valid email address"
id="email-dbf3" name="email"
class="u-border-1 u-border-grey-30 u-input u-input-rectangle u-white"
required="true" autofocus="autofocus">
</div>
<div class="u-form-email u-form-group u-form-group-2">
<label for="name-dbf3"
class="u-form-control-hidden u-label">Name</label>
<input type="text" placeholder="Enter a valid password" id="name-dbf3"
name="password"
class="u-border-1 u-border-grey-30 u-input u-input-rectangle u-white"
required="true">
</div>
<div class="u-align-left u-form-group u-form-submit u-form-group-3">
<button type="submit" name="submit" class="btn btn-primary btn-lg">Login
</button>
</div>
<p th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Description errors</p>
</form>
</div>

提交表单时调用的 Controller 方法是这样的

@PostMapping("/home")
public String authenticate(@ModelAttribute IndexFormBean indexFormBean, Model model){
String loginResponse = userService.login(indexFormBean.getEmail(),
indexFormBean.getPassword());
if(StringUtils.isEmpty(loginResponse)){
//Some error that is returned from the service layer
return "index";
}
return "home";
}

现在,如果 authenticate 方法需要在 UI (index.html) 上显示一些错误,我该怎么做呢?

最佳答案

在 MVC 中有两种方法可以处理错误消息。

  1. 使用error.html 模板。如果在 Controller 方法中遇到任何未捕获的异常,Spring boot 将自动使用此模板。
  2. 在您的 Controller 方法中捕获异常并将适当的错误消息添加到您的模型。然后,您可以在 index.htmlhome.html
  3. 中的某处使用错误消息

你可以这样做,

if(StringUtils.isEmpty(loginResponse)){
model.addAttribute("errorMessage","Login failed");
return "index";
}

在你的 index.html 中,添加类似的东西,

    <span th:if="${errorMessage}"  th:text="${errorMessage}">Error</span>

关于spring-boot - Thymeleaf 和 Spring 引导中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63654243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com