练手注解和验证器_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 练手注解和验证器

练手注解和验证器

 2014/11/18 16:10:21  kilobug  程序员俱乐部  我要评论(0)
  • 摘要:基于spring的validation及hibernatevalidation特点:1、支持spring注入(没找到hibernatevalidation如何注入)2、自定义注解验证(虽然hibernatevalidation也支持)3、写了一个验证码校验,和验证引用的DIY注解(指向)使用例子:Userentitypackageorg.kilobug.news.entity;importjavax.validation.constraints.Min;importlombok.Data
  • 标签:注解

基于spring的validation及hibernate validation

特点:

1、支持spring注入(没找到hibernate validation如何注入)

2、自定义注解验证(虽然hibernate validation也支持)

3、写了一个验证码校验,和验证引用的DIY注解(指向)

?

使用例子

User entity

?

class="java" name="code">package org.kilobug.news.entity;

import javax.validation.constraints.Min;

import lombok.Data;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;

@Data
public class User {
	private Long id;
	@Min(0)
	private Long roleId = 0L;
	@Email
	private String email;
	@Min(0)
	private Long mobile = 0L;
	private byte[] password;
	@Length(min=6, max=32)
	private String plainPassword;
	private byte[] salt;
	private String plainSalt;
	private Long creationTime;
	private Long creationIp;
	private Long lastLoginTime = 0L;
	private Long lastLoginIp = 0L;
	private Long statusId = 0L;
}

?

?

UserAdd entity

?

package org.kilobug.news.service.entity;
import lombok.Data;

import org.hibernate.validator.constraints.NotBlank;
import org.kilobug.news.entity.User;
import org.kilobug.validator.constrains.BaseValidate;
import org.kilobug.validator.constrains.Captcha;

public @Data class UserAdd {
	@BaseValidate(value=User.class) // 根据User的email字段的规则验证
	private String email;
	@BaseValidate(value=User.class) // 根据User的plainPassword字段的规则验证
	private String plainPassword;
	@NotBlank @Captcha // 自定义注解验证器,支持注入
	private String captcha;
}

?

?

使用:

?

package org.kilobug.news.validator;

import org.kilobug.news.entity.User;
import org.kilobug.news.service.entity.UserAdd;
import org.kilobug.validator.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

@Component
public class UserAddValidator implements Validator {
	@Autowired private ValidatorUtil validator;

	@Override
	public boolean supports(Class<?> clazz) {
		return UserAdd.class.equals(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		if(validator.vaildate(target, errors) == false) return;
		UserAdd entity = (UserAdd) target;
		// :TODO 进一步自定义判断
	}

}

?

?

?

  • org.kilobug.validator.jar (6.3 KB)
  • 下载次数: 1
发表评论
用户名: 匿名