I'm certainly new to Thymeleaf and hesitating to moving to this new technology. Current problem I encountered is that iterating errors and display user friendly error message. I might be missing something, but what I encountered are two issues here:
1) In controller.
When using jsp with Spring MVC, if a method has errors, we can simply add it to BindingResult object, and it looks Spring MVC does the binding to the form returned. We don't need to add it to form or modal object.
This seems not working with Thymeleaf. I had to add it to modal object:
Code: Select all
@RequestMapping(value="/actionPath", method=RequestMethod.GET)
public ModelAndView updateProduct(@RequestParam(@ModelAttribute("myForm") MyForm myForm,
BindingResult errors, ModelMap model, HttpServletRequest request){
....
....
ModelAndView ret = new ModelAndView(view);
ret.getModelMap().addAttribute("errors", errors);
return ret;
}
2) In the view (thymeleaf HTML page)
As in jsp, we can use Spring tag to iterate all errors including errors of specific fields and errors at form level like:
Code: Select all
<div>
<spring:hasBindErrors name="productForm">
<spring:bind path="productForm.*">
<c:forEach var="error" items="${status.errorMessages}">
<ul><li><font color="red"><c:out value="${error}"/></font></li></ul>
</c:forEach>
</spring:bind>
</spring:hasBindErrors>
</div>
This will display the user friendly error message defined in Messages.properties on the page.
Try to do similar iteration on thymeleaf page:
Code: Select all
<ul th:if="${errors != null}" class="error">
<li th:each="err : ${errors}" th:text="${err}">Input is incorrect</li>
</ul>
This displays the actual error object. Using "#{err}" seems better, but it seems it can't find the localized string. How should I fix it so I can have the same effect as with jsp?
Another problem is to handle global error not related to any field, but the form or backend issue. Don't know how to it. Googled it for a while, but didn't find any answer.
Appreciate any help!
-Charlie