Note that if you use Bean Validation to check the input and output an error message, you need to be careful if you want to include the field name in the content.
: star: I have a Sample Project on GitHub
If you want to output the following message to the following form
UserForm.java
import java.io.Serializable;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class UserForm implements Serializable {
private static final long serialVersionUID = 1L;
@NotNull(message = "{userForm.name}")
@Size(min = 1, max = 20, message = "{userForm.name}")
private String name;
// getter/setter omitted
"[name] is not null."
--Cannot output with LocalValidatorFactoryBean
UserControl.java
import javax.validation.Validator;
@Resource
private Validator validator;
//Actual processing part
Set<ConstraintViolation<UserForm>> violations = validator.validate(form);
if (!violations.isEmpty()) {
for (ConstraintViolation<UserForm> v : violations) {
log.info(v.getMessage());
}
}
application-context.xml
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
ValidationMessage.properties
userForm.name={0} is not null.
I thought that {0} would be replaced with the field name, but the actual output result is output without being replaced as shown below.
{0} is not null.
--Field name replacement seems to be realized by data binding provided by Spring
That is, use @Validated as follows
UserControl.java
@RequestMapping(value = "create", method = RequestMethod.POST, params = "confirm")
public String createConfirm(@Validated UserForm form, BindingResult result) {
if (result.hasErrors()) {
return "user/createForm";
}
return "user/createConfirm";
}
Or use Smart Validator
UserControl.java
import org.springframework.validation.SmartValidator;
@Resource //Smart Validator<mvc:annotation-driven>Bean definition is not required because it can be used if is set.
private SmartValidator smartValidator;
@RequestMapping(value = "create", method = RequestMethod.POST, params = "confirm")
public String createConfirm(UserForm form, BindingResult result) {
smartValidator.validate(form, result);
if (result.hasErrors()) {
return "user/createForm";
}
return "user/createConfirm";
}
--LocalValidatorFactoryBean cannot output the error message including the field name. --Because it is realized by Spring data binding --Use @Validated or SmartValidator to achieve
Recommended Posts