1凳干、接口參數(shù) 都以對接收 (@RequestBody Login login)
2、所有接口參數(shù)實體類 繼承 BaseValidate (Login extends BaseValidate)
3被济、需要驗證的字段加上 @RequireField救赐、@LengthIllegal
public class Login extends BaseValidate
{
@RequireField
String username;
@RequireField
String password;
}
4、在調(diào)用后臺接口函數(shù)之前只磷,利用AOP執(zhí)行參數(shù)驗證经磅,參數(shù)實體調(diào)用驗證基類validate函數(shù),會執(zhí)行相應的requireField函數(shù) 钮追。预厌。。等待解析函數(shù)元媚, 判斷字段上是否存在這些注解轧叽、存在就執(zhí)行驗證
@RequestMapping(method = RequestMethod.POST,value = "login")
@ValidateParameter
@PrintParameter(description = "登錄接口")
public ValidateResult login(HttpServletRequest request, @RequestBody Login login) throws ParseException
{
//業(yè)務(wù)邏輯
return validateResult;
}
驗證注解
/**
* 打印參數(shù)
*
* @author MENG
* @version 2017/7/13
* @see
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValidateParameter
{
/**
* 函數(shù)描述
*
* @return
*/
String description() default "";
}
驗證注解 對應的實現(xiàn)類
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()
{
}
/**
* 環(huán)繞
* @param
* @param pjp
* @return
* @throws Throwable
*/
@Around("pointCutMethod()")
public Object Around(ProceedingJoinPoint pjp)
throws Throwable
{
//參數(shù)值
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());
}
}
注解實現(xiàn)類調(diào)用的驗證方法
驗證 基類
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<String,Object> 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); // 設(shè)置屬性是可以訪問的(私有的也可以)
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<String,Object> 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();//結(jié)束長度
field.setAccessible(true); // 設(shè)置屬性是可以訪問的(私有的也可以)
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();
}
/**
* 公共驗證函數(shù)
*
* @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;
/**
* 長度結(jié)束范圍
*
* @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<T> implements Serializable
{
private static final long serialVersionUID = -6139677251863746424L;
/**
* 返回代碼 00000 為OK 其他 error
*/
private String code = "00000";
/**
* 返回信息 SUCCESS
*/
private String message = "SUCCESS";
/**
* 返回數(shù)據(jù)
*/
private T data;
}
錯誤代碼 和 提示
package com.vali;
/**
* 返回給前臺的 錯誤代碼 和 提示
*
* @author MENG
* @version 2018/9/15
* @see
*/
public enum CodeEnum
{
//當code == 00000 程序調(diào)用成功
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
{
/**
* 返回結(jié)果 常量字段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<String,Object> returnSuccess()
{
Map<String, Object> 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<String,Object> returnSuccessAndData(Object data)
{
Map<String, Object> 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<String,Object> returnError(String code,String message)
{
Map<String, Object> resultMap = new HashMap<>(4);
resultMap.put(Constants.RESULT_CODE, code);
resultMap.put(Constants.RESULT_MSG, message);
return resultMap;
}
/**
* 返會 錯誤
*
* @return
*/
public static Map<String,Object> returnError(CodeEnum codeEnum)
{
Map<String, Object> resultMap = new HashMap<>(4);
resultMap.put(Constants.RESULT_CODE, codeEnum.getCode());
resultMap.put(Constants.RESULT_MSG, codeEnum.getMessage());
return resultMap;
}
/**
* 返會 錯誤
*
* @return
*/
public static Map<String,Object> returnError(String code,String message,Object object)
{
Map<String, Object> 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<String,Object> returnError(CodeEnum codeEnum,Object object)
{
Map<String, Object> 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();
}
}