From the thymeleaf guide, I have seen the following code snippet:
<ul th:if="${#fields.hasErrors('global')}">
<li th:each="err : ${#fields.errors('global')}" th:text="${err}">Input is incorrect</li>
</ul>
So, I m thinking if there is a way that I can pass error message from the Spring MVC controller and display the error somewhere on the page using the above code.
I have seen some online resources using BindingResult on the method signature as below.
bindingResult.rejectValue("username", "username.notvalid", "Username is not valid");
But what if the controller does not validate any objects? Will I still be able to use bindingResult?
I think I can also add error message as key pair into the model as below.
model.addAttributes("error","error message");
But, I want to know if there is some standard way of handling error in the Spring controller.
Should I use exception handling instead? But how can I pass error message back to the view?
Thanks
Updated use case:
For example, in method A, an error was detected as below.
public String methodA (Model m, RedirectAttributes model){
if (error == true){
model.addFlashAttribute("error.message","String");
return "redirect:MethodB";
}
}
public String methodB(Model m){
if(m.containsAttribute("error.message"){
//Way to pass the error to view page for display.
}
}
Should the error be handled in such way? The reason it goes through the second action is because there are certain data needed to be displayed on the final view page.