In my spring boot thymeleaf application, i am struggling to figure out how to display the error message returned from the service layer onto the UI.
My UI Code (index.html) is
<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>
The controller method invoked when the form is submitted is like this
@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";
}
Now if the authenticate method needs to show some error on the UI (index.html) how can I do so ?
There are two ways you can handle error messages in MVC.
error.html template. Spring boot will automatically use this template if it encounters any uncaught exceptions within controller method.model. You can then use the error message somewhere in your index.html or home.htmlYou can do something like,
if(StringUtils.isEmpty(loginResponse)){
model.addAttribute("errorMessage","Login failed");
return "index";
}
And in your index.html, add something like,
<span th:if="${errorMessage}" th:text="${errorMessage}">Error</span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With