练手注解和验证器

基于spring的validation及hibernate validation

特点:

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

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

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

 

使用例子:

User entity

 

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 进一步自定义判断
	}

}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值