Combine Spring validator and Hibernate validator
By:Roy.LiuLast updated:2019-08-17
In this article, we will show you how to validate the submitted form values with Spring validator and Hibernate Validator (bean validation).
Technologies used :
- Spring 4.1.6.RELEASE
- Hibernate Validator 5.1.3.Final
1. Hibernate Validator
The Hibernate validator will be fired if @Valid is provided.
import org.hibernate.validator.constraints.NotEmpty; public class User { @NotEmpty String name; //...
@RequestMapping(value = "/users", method = RequestMethod.POST) public String saveOrUpdateUser( @ModelAttribute("userForm") @Valid User user, BindingResult result, Model model) { if (result.hasErrors()) { //... } else { //...
2. Spring Validator
If you enabled the Spring validator via @InitBinder, the Hibernate bean validation will be ignore.
public class UserFormValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return User.class.equals(clazz); @Override public void validate(Object target, Errors errors) { User user = (User) target; //validate something else
@Controller public class UserController { @InitBinder protected void initBinder(WebDataBinder binder) { binder.setValidator(new UserFormValidator());
3. Hibernate Validator + Spring Validator
To have both Hibernate and Spring validator. Remove the @InitBinder and fire the Spring validator manually.
@Controller public class UserController { /*@InitBinder protected void initBinder(WebDataBinder binder) { binder.setValidator(new UserFormValidator()); }*/ @RequestMapping(value = "/users", method = RequestMethod.POST) public String saveOrUpdateUser( @ModelAttribute("userForm") @Valid User user, BindingResult result, Model model) { //run Spring validator manually new UserFormValidator().validate(user, result); if (result.hasErrors()) { //... } else { //...
In the above example, the submitted “userForm” model will first validate by Hibernate validator, then follow by Spring validator.
References
From:一号门
Previous:Spring Mixing XML and JavaConfig
COMMENTS