自定义接口验证规则

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;
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值