Spring JSR-303 with error tag: error
I am trying to use validation JSR-303
and display it on a page jsp
. Here is a piece of code jsp
that shows the error:
<c:set var="Error">
<form:errors path="name"/>
</c:set>
...
<spring:transform value="${Error}"/>
In my controller, I have the following:
@PostMapping(params = "next")
public String next(@Valid @ModelAttribute(COMMAND_NAME) final ProjectNewDetailsCommand cmd,
final Errors errors,
final Model model,
final HttpServletRequest request) {
First, the solution that worked for me was to write a custom class Validator
:
@Override
public void validate(Object o, Errors errors) {
errors.pushNestedPath("project");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "error.project.creation.name.required");
errors.popNestedPath();
}
In this case, the appropriate message from was applied messages.properties
and shown in the user interface:
error.project.creation.name.required=The name must not be blank.
Here's another case where I use annotation JSR-303
:
public class Project {
...
@Size(max = 100, message = "error.project.creation.size")
private String name;
In messages.properties
there is a post under the key error.project.creation.size
, I also tried adding a post with a key Size.command.project.name
as mentioned in some sources. Error
the object in the controller is also not empty and contains validation errors. But when I use this approach with JSR-303
I got the following error:
Caused by: javax.servlet.jsp.JspTagException: No message found under code 'Size' for locale 'en_US'.
at org.springframework.web.servlet.tags.MessageTag.doEndTag(MessageTag.java:200)
This means it is Spring
trying to apply an error code Size
instead of error.project.creation.size
or for some reason Size.command.project.name
. Any ideas why this is happening and how to fix it?
source to share
Finally, I was able to find the source of the problem. There was a tag in the code for rendering warnings spring:message
:
<spring:message code="${error.code}" arguments="${error.arguments}"/>
If works like this: it looks for the last code from the array codes
in the class Errors
(see DefaultMessageSourceResolvable.getCode ) and why it couldn't find the message Size
and didn't select defaultMessage
generated with hibernate validator or custom.
The simple solution in this case was to add an attribute text
:
<spring:message code="${error.code}" arguments="${error.arguments}" text="${error.defaultMessage}"/>
source to share