I am using Spring Boot 2.4.1 with Thymeleaf, and OpenJDK 11.0.9.1 on Ubuntu 20.10. I have tagged the entities with @NotNull and other tags, and the @Valid tag seems to be working fine in the controller's method that handles POST requests, because on error it returns me to the original page. However, th:if...th:errors
in the Thymeleaf template are not working to show the corresponding error message.
The Thymeleaf template (/editor
) includes a form:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<body>
...
<form method="POST" th:object="${competence}">
<h3>Additional information</h3>
<label for="compname">Name:</label>
<input type="text" id="compname" th:field="*{name}" />
<span class="validationError"
th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Error</span><br/>
<label for="compdesc">Description:</label>
<textarea class="description" id="compdesc" th:field="*{description}" />
<button>Regístrala</button>
</div>
</form>
Whereas the controller includes a method for handling POST requests:
@Slf4j
@Controller
@RequestMapping("/editor")
public class CompetenceEditorController {
...
@PostMapping
public String processCompetence(@Valid CompetenceEntity competence,
final BindingResult bindingResult, final Model model) {
// Checking for errors in constraints defined in the class CompetenceEntity.
if (bindingResult.hasErrors()) {
return "editor";
} else {
// Save the competence
log.info("Processing competence: " + competence);
CompetenceEntity saved = competenceRepository.save(competence);
return "redirect:/competence-saved";
}
}
If I fill name and description, the process continues, but if I leave name empty, the code sends me back to the /editor
page, but there is no error message. The span
element dissappears before and after the error.
EDIT
I thought that the suggestion by @dirk-deyne worked, but only does so if (1) I run the Spring Boot on the previous code, (2) I leave name blank (and I get back to the same page without error message), (3) I get Boot down, "fix" the code, and run it again, (4) leave name blank again, and again, and again.
But if I leave the page, and then I get back again, I get the error message:
There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/editor.html]")
...
Caused by: org.attoparser.ParseException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "editor" - line 51, col 46)
Where line 51 is
<input type="text" id="compname" th:field="*{name}" />
And column 46 (including spaces) is the start of th:field
. By the way, the @GetMapping method has the following line
model.addAttribute("competence", new CompetenceEntity());
and that is why I was using th:object="${competence}"
instead of th:object="${competenceEntity}"
.