1、创建自定义的注解类验证规则
package com.gosuncn.orderManage.web.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 长度注解,用于验证String的长度,包括最小长度,最大长度和是否为空串
*
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Length {
String name() default "";
/**
* 字段最小长度
*/
int min() default 1;
/**
* 字段最大长度
*/
int max() default 100;
/**
* 能否为空
*/
boolean canBlank() default false;
}
2、在实体类中对相应的字段加以注解
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.format.annotation.DateTimeFormat;
import com.alibaba.fastjson.annotation.JSONField;
import com.gosuncn.orderManage.web.util.Length;
@Entity
@Table(name = "order")
public class AlarmOrder implements Serializable {
private static final long serialVersionUID = 4642078379320703633L;
/**
* 工单ID
*/
@Id
@Column(name="ID")
@Length(max = 36)
private String id;
/**开始时间
*/
@Column(name="TIME")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@JSONField(format="yyyy-MM-dd HH:mm:ss")
@Length
private Date time;
/**
* 备注
*/
@Column(name="REMARK")
private String remark;
}
3、编写接口验证实用类
/**
* 参数验证,配合响应的注解使用<br>
*
* @param object 验证对象
* @return 根据规则验证成功则返回true,否则false
* @throws IllegalAccessException
* @see Length
*/
public static boolean dataValid(Object object) {
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
// 字符串验证
Length length = field.getAnnotation(Length.class);
if (length != null) {
boolean isAccessible = field.isAccessible();
field.setAccessible(true);
String value="";
try {
Object object2 = field.get(object);
if(object2!=null){
value =object2.toString();
}
} catch (IllegalAccessException e) {
LogUtils.error("获取字段值失败!", e);
throw new RuntimeException("获取字段值失败!");
} finally {
field.setAccessible(isAccessible);
}
if (!length.canBlank() && isBlank(value)) {
LogUtils.error("参数‘{}’不能为空", field.getName());
return false;
} else{
if (value.length() < length.min()) {
LogUtils.error("参数‘{}’长度不能小于{}", field.getName(), length.min());
return false;
}
if (value.length() > length.max()) {
LogUtils.error("参数‘{}’长度不能大于{}", field.getName(), length.max());
return false;
}
}
}
}
return true;
}
private static boolean isBlank(String value) {
return value == null || value.trim().length() == 0;
}