需要提供三个注解
@CheckParam
,标记需要检查参数的方法
@IsStrNotBlank
,标记检查字符串是否为空
@IsStrNotBlank
,标记检查对象是否为null
/**
* 校验标记注解
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckParam {
}
/**
* 不能为null
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface IsNotNull {
String value();
}
/**
* 不能为空
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface IsStrNotBlank {
String value();
}
AOP部分
@Aspect
@Component
@Slf4j
public class CheckParamAop {
@Autowired
private HttpServletResponse rsp;
@Around("@annotation(com.doria.electronicContract.annotation.CheckParam)")
public Object repeatSubmitIntercept(ProceedingJoinPoint pjp) throws Throwable {
rsp.setContentType("text/json;charset=UTF-8");
Object[] args = pjp.getArgs();
MethodSignature signature = (MethodSignature) pjp.getSignature();
Annotation[][] parameterAnnotations = signature.getMethod().getParameterAnnotations();
boolean flag = true;
ArrayList<String> blankStrParam = new ArrayList<>();
ArrayList<String> nullObjParam = new ArrayList<>();
for (int i = 0; i < args.length; i++) {
for (Annotation annotation : parameterAnnotations[i]) {
if (annotation instanceof IsStrNotBlank) {
if (args[i] == null || "".equals(args[i])) {
flag = false;
String value = ((IsStrNotBlank) annotation).value();
blankStrParam.add(value);
}
} else if (annotation instanceof IsNotNull) {
if (args[i] == null) {
flag = false;
String value = ((IsNotNull) annotation).value();
nullObjParam.add(value);
}
}
}
}
if (flag) {
return pjp.proceed();
}
rsp.setStatus(400);
String json = getBadParamResult(blankStrParam, nullObjParam).toString();
rsp.getWriter().write(json);
rsp.getWriter().close();
log.error("参数异常,{}",json);
return null;
}
// 传入异常参数生成响应Json
public Object getBadParamResult(ArrayList<String> badStrParam, ArrayList<String> nullObjParam) {
String msg = "";
if (badStrParam.size() != 0) {
msg = msg + "参数" + badStrParam + "不能为null或者空";
}
if (nullObjParam.size() != 0) {
if (msg.length() > 1)
msg = msg + ",";
msg = msg + "参数" + nullObjParam + "不能为null";
}
return "{\"code\":400,\"msg\":\"" + msg + "\"}";
}
}
使用
请求以及响应
使用
请求&响应