可以实现接口调用验证签名、参数判断等扩展。
1、注解方法
/**
* 自定义注解签名参数验证
* xuxx
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ParamValidate {
String value() default "";
}
2、切面处理类
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* 切面处理类
* xuxx
*/
@Aspect
@Component
public class ValidateAspect {
@Autowired
private ValidateSignService validateSignService;
@Before("@annotation(org.xxx.service.ParamValidate)")
public void before(JoinPoint joinPoint) throws Exception {
//MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
//请求的参数
Object[] args = joinPoint.getArgs();
Map<String, String> map = (Map<String, String>) args[0];
validateSignService.validateSign(map);
}
}
3、业务处理接口
import java.util.Map;
public interface ValidateSignService {
public void validateSign(Map<String, String> map) throws Exception;
}
4、业务处理接口实现类
@Service
public class ValidateSignServiceImpl implements ValidateSignService {
@Override
public void validateSign(Map<String, String> map) throws Exception {
if (!CollectionUtils.isEmpty(map)) {
String parms = map.get("one");
String sign = map.get("sign");
if (!StringUtils.isEmpty(sign) && !"null".equals(sign)) {
String key = String.valueOf(CommonConst.configCache.get("key"));
if (StringUtils.isEmpty(parms) || "null".equals(parms)) {
parms = "";
}
boolean flag = SignUtil.verifySignMd5_HEX(parms, sign, key, CommonConst.CHARSET);
if (!flag) {
throw new ValidateException("验签失败,请检查签名是否正确!");
}
} else {
throw new ValidateException("签名sign参数不能为空,请检查!");
}
} else {
throw new ValidateException("参数不能为空,请检查!");
}
}
}
5、定义ValidateException异常类
public class ValidateException extends RuntimeException {
public ValidateException(String msg) {
super(msg);
}
}
6、全局捕获ValidateException异常类
**
* 全局异常捕捉
* xuxx
*/
@RestControllerAdvice
@ControllerAdvice
public class GlobalExceptionHandler {
//返回值String可自定义为返回的封装类
@ExceptionHandler(ValidateException.class)
public JsonData handlerValidateException(ValidateException ex) {
JsonData jd = new JsonData();
jd.setStatus(CommonConst.FAIL_TYPE);
jd.setData(ex.getMessage());
return jd;
}
}
7、在对应的方法上面使用注解即可
*/
@PostMapping("/getSensorType")
@ParamValidate
@ResponseBody