Combine Spring validator and Hibernate validator

摘要: In this article, we will show you how to validate the submitted form values with Spring validator and Hibernate Validator (bean validation).

In this article, we will show you how to validate the submitted form values with Spring validator and Hibernate Validator (bean validation).

Technologies used :

  1. Spring 4.1.6.RELEASE
  2. 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

  1. Validation, Data Binding, and Type Conversion
  2. Validating Form Input

上一篇: Spring Mixing XML and JavaConfig
下一篇: Eclipse How to change web project context root
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号