后台接口参数自动化注解验证 @RequireField、@LengthIllegal、@EmailIllegal

1、接口参数 都以对接收 (@RequestBody Login login)

2、所有接口参数实体类 继承 BaseValidate (Login extends BaseValidate)

3、需要验证的字段加上 @RequireField、@LengthIllegal

public class Login extends BaseValidate
{  
    @RequireField
    String username;

    @RequireField
    String password;
}

4、在调用后台接口函数之前,利用AOP执行参数验证,参数实体调用验证基类validate函数,会执行相应的requireField函数 。。。等待解析函数, 判断字段上是否存在这些注解、存在就执行验证

    @RequestMapping(method = RequestMethod.POST,value = "login")
    @ValidateParameter
    @PrintParameter(description = "登录接口")
    public ValidateResult login(HttpServletRequest request, @RequestBody Login login) throws ParseException
    {
        //业务逻辑
        return validateResult;
    }

验证注解

/**
 * 打印参数
 *
 * @author MENG
 * @version 2017/7/13
 * @see
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValidateParameter
{
    /**
     * 函数描述
     *
     * @return
     */
    String description()  default "";
}

验证注解 对应的实现类

package com.ec.biz.serv.util.validate.annotation;

import com.ec.biz.serv.util.validate.vali_util.ValidateConstants;
import com.ec.biz.serv.util.validate.vali_util.ValidateResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


/**
 * 注解RemoveEmptyOrNullParamter aop
 *
 * @author MENG
 * @version 2017/7/13
 * @see
 */
@Aspect
@Component
public class ValidateParameterAspect
{
    private static Logger logger = LoggerFactory.getLogger(ValidateParameterAspect.class);

    /**
     * 切入点
     */
    @Pointcut("@annotation(com.ec.biz.serv.util.validate.annotation.ValidateParameter)")
    public void pointCutMethod()
    {
    }

    /**
     * 环绕
     * @param
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("pointCutMethod()")
    public Object Around(ProceedingJoinPoint pjp)
        throws Throwable
    {
        //参数值
        Object[] objects = pjp.getArgs();

        for(Object object : objects)
        {
            Method mothod = null;

            try
            {
                mothod = object.getClass().getMethod(ValidateConstants.BASE_VALIDATE_METHOD_NAME);
            }
            catch (NoSuchMethodException e)
            {
                continue;
            }

            ValidateResult validateResult = (ValidateResult)mothod.invoke(object);

            if(!validateResult.getCode().equals(ValidateConstants.RESULT_SUCCESS_CODE))
            {
                return validateResult;
            }
            else
            {
                return pjp.proceed(pjp.getArgs());
            }
        }

        return pjp.proceed(pjp.getArgs());
    }

}

注解实现类调用的验证方法

验证 基类

package com.vali;

import com.annotation.EmailIllegal;
import com.annotation.LengthIllegal;
import com.annotation.RequireField;

import java.lang.reflect.Field;
import java.util.Map;



/**
 * 后台验证 基类
 *
 * @author MENG
 * @version 2019/1/21
 * @see
 */
public class BaseValidate
{
    /**
     * 公共 验证必填字段
     *
     *
     * @return
     */
    public Map requireField()
        throws IllegalAccessException
    {
        Field[] fields = this.getClass().getDeclaredFields();

        for(Field field : fields)
        {
            if (field.isAnnotationPresent(RequireField.class))
            {
                RequireField obj = field.getAnnotation(RequireField.class);

                String description = obj.description();// 获取注解描述

                field.setAccessible(true); // 设置属性是可以访问的(私有的也可以)

                Object value = field.get(this);

                if(value == null || "".equals(value.toString()))
                {
                    if(description != null)
                    {
                        return Utils.returnError(CodeEnum.REQUIRE_FIELD.getCode(), description);
                    }
                    else
                    {
                        return Utils.returnError(CodeEnum.REQUIRE_FIELD.getCode(), CodeEnum.REQUIRE_FIELD.getMessage());
                    }
                }
            }
        }

        return Utils.returnSuccess();
    }


    /**
     * 公共 验证字段长度合法性
     *
     *
     * @return
     */
    public Map lengthIllegal()
        throws IllegalAccessException
    {
        Field[] fields = this.getClass().getDeclaredFields();

        for(Field field : fields)
        {
            if (field.isAnnotationPresent(LengthIllegal.class))
            {
                LengthIllegal obj = field.getAnnotation(LengthIllegal.class);

                String description = obj.description();// 获取注解描述

                int start = obj.start();//开始长度

                int end = obj.end();//结束长度

                field.setAccessible(true); // 设置属性是可以访问的(私有的也可以)

                Object value = field.get(this);

                //判断是否为空
                if(value == null || "".equals(value))
                {
                    if(description != null)
                    {
                        return Utils.returnError(CodeEnum.LENGTH_ILLEGAL.getCode(), description);
                    }
                    else
                    {
                        return Utils.returnError(CodeEnum.LENGTH_ILLEGAL.getCode(), CodeEnum.LENGTH_ILLEGAL.getMessage());
                    }
                }

                //判断长度是否合法
                if(value.toString().length() < start || value.toString().length() > end)
                {
                    if(description != null)
                    {
                        return Utils.returnError(CodeEnum.LENGTH_ILLEGAL.getCode(), description);
                    }
                    else
                    {
                        return Utils.returnError(CodeEnum.LENGTH_ILLEGAL.getCode(), CodeEnum.LENGTH_ILLEGAL.getMessage());
                    }
                }
            }
        }

        return Utils.returnSuccess();
    }

/**
     * 公共验证函数
     *
     * @return
     * @throws IllegalAccessException
     */
    public ValidateResult validate()
        throws IllegalAccessException, InvocationTargetException
    {
        ValidateResult validateResult = null;

        validateResult = requireField();

        if(!validateResult.getCode().equals(ValidateConstants.RESULT_SUCCESS_CODE))
        {
            return validateResult;
        }

        validateResult = lengthIllegal();

        if(!validateResult.getCode().equals(ValidateConstants.RESULT_SUCCESS_CODE))
        {
            return validateResult;
        }
        return ValidateUtil.returnSuccess();
    }
}

注解

package com.annotation;

import java.lang.annotation.*;


/**
 * 必填字段
 *
 * @author MENG
 * @version 2019/1/21
 * @see
 */
@Target({ ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequireField
{
    /**
     * 用于 描述字段的名称 也可用于提示用户
     *
     * @return
     */
    String description() default "";

}

package com.annotation;

import java.lang.annotation.*;


/**
 * 字段长度验证
 *
 * @author MENG
 * @version 2019/1/21
 * @see
 */
@Target({ ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LengthIllegal
{
    /**
     * 长度开始范围
     *
     * @return
     */
    int start() default 8;

    /**
     * 长度结束范围
     *
     * @return
     */
    int end() default 100;

    /**
     * 用于 描述字段的名称 也可用于提示用户
     *
     * @return
     */
    String description() default "";

}

package com.ec.biz.serv.util.validate.vali_util;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;


/**
 * 验证返回model
 *
 * @author MENG
 * @version 2019/3/27
 * @see
 */
@Data
public class ValidateResult implements Serializable
{
    private static final long serialVersionUID = -6139677251863746424L;

    /**
     * 返回代码 00000 为OK  其他 error
     */
    private String code = "00000";

    /**
     * 返回信息 SUCCESS
     */
    private String message = "SUCCESS";

    /**
     * 返回数据
     */
    private T data;
}



错误代码 和 提示

package com.vali;

/**
 * 返回给前台的 错误代码 和 提示
 *
 * @author MENG
 * @version 2018/9/15
 * @see
 */
public enum CodeEnum
{
    //当code == 00000 程序调用成功
    SUCCESS("00000","SUCCESS"),
    REQUIRE_FIELD("00001","不能为空."),
    LENGTH_ILLEGAL("00002","长度不合法."),
    EMAIL_ILLEGAL("00003","邮箱格式不合法."),

    SYSTEM_ERROR("99999","后台维护中,请稍后再试."),
    ;


    private String code;

    private String message;

    CodeEnum(String code, String message)
    {
        this.code = code;

        this.message = message;
    }

    public String getCode()
    {
        return code;
    }

    public String getMessage()
    {
        return message;
    }
}

常量

package com.vali;

/**
 * 常量
 *
 * @author MENG
 * @version 2018/8/28
 * @see
 */
public class Constants
{
    /**
     *  返回结果 常量字段KEY-------------------START
     */
    public static final String RESULT_CODE = "code";

    public static final String RESULT_SUCCESS_CODE = "00000";

    public static final String RESULT_MSG = "message";

    public static final String RESULT_DATA = "data";

    //---------------------------------------END

}

工具类

package com.vali;

import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 工具类
 *
 * @author MENG
 * @version 2018/7/26
 * @see
 */
public class Utils
{
/**
     * 返会 成功
     *
     * @return
     */
    public static Map returnSuccess()
    {
        Map resultMap = new HashMap<>(4);

        resultMap.put(Constants.RESULT_CODE, CodeEnum.SUCCESS.getCode());

        resultMap.put(Constants.RESULT_MSG, CodeEnum.SUCCESS.getMessage());

        return resultMap;
    }

    /**
     * 返会 成功
     *
     * @return
     */
    public static Map returnSuccessAndData(Object data)
    {
        Map resultMap = new HashMap<>(4);

        resultMap.put(Constants.RESULT_CODE, CodeEnum.SUCCESS.getCode());

        resultMap.put(Constants.RESULT_MSG, CodeEnum.SUCCESS.getMessage());

        resultMap.put(Constants.RESULT_DATA, data);

        return resultMap;
    }

    /**
     * 返会 错误
     *
     * @return
     */
    public static Map returnError(String code,String message)
    {
        Map resultMap = new HashMap<>(4);

        resultMap.put(Constants.RESULT_CODE, code);

        resultMap.put(Constants.RESULT_MSG, message);

        return resultMap;
    }

    /**
     * 返会 错误
     *
     * @return
     */
    public static Map returnError(CodeEnum codeEnum)
    {
        Map resultMap = new HashMap<>(4);

        resultMap.put(Constants.RESULT_CODE, codeEnum.getCode());

        resultMap.put(Constants.RESULT_MSG, codeEnum.getMessage());

        return resultMap;
    }

    /**
     * 返会 错误
     *
     * @return
     */
    public static Map returnError(String code,String message,Object object)
    {
        Map resultMap = new HashMap<>(4);

        resultMap.put(Constants.RESULT_CODE, code);

        resultMap.put(Constants.RESULT_MSG, message);

        resultMap.put(Constants.RESULT_DATA, object);

        return resultMap;
    }

    /**
     * 返会 错误
     *
     * @return
     */
    public static Map returnError(CodeEnum codeEnum,Object object)
    {
        Map resultMap = new HashMap<>(4);

        resultMap.put(Constants.RESULT_CODE, codeEnum.getCode());

        resultMap.put(Constants.RESULT_MSG, codeEnum.getMessage());

        resultMap.put(Constants.RESULT_DATA, object);

        return resultMap;
    }

    /**
     * 检查Email 是否合法
     * @param email
     * @return
     */
    public static boolean checkEmail(String email)
    {
        String regex = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";

        Pattern p = Pattern.compile(regex);

        Matcher m = p.matcher(email);

        return m.matches();
    }
}

你可能感兴趣的:(后台接口参数自动化注解验证 @RequireField、@LengthIllegal、@EmailIllegal)