200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > 自定义注解+切面处理+全局异常处理

自定义注解+切面处理+全局异常处理

时间:2021-02-03 20:30:24

相关推荐

自定义注解+切面处理+全局异常处理

可以实现接口调用验证签名、参数判断等扩展。

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.ponent;import java.util.Map;/*** 切面处理类* xuxx*/@Aspect@Componentpublic class ValidateAspect {@Autowiredprivate 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、业务处理接口实现类

@Servicepublic class ValidateSignServiceImpl implements ValidateSignService {@Overridepublic 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@ControllerAdvicepublic 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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。