美文网首页
利用aop 实现spring boot restful cont

利用aop 实现spring boot restful cont

作者: 笛声hk | 来源:发表于2019-03-02 17:05 被阅读0次

[toc]

前言:

对于某些简单字段的检验 都有一定的共同和普遍性.利用aop 获取参数 并根据校验规则统一检验是个不错的选择.

1. 创建字段统一校验规则

在 application.yml中创建map类型

validateRules:
  code: required
  name: required

2. 自定义注解

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ValidateAnnotaion {
    String []value();
}

3.切面类

@Component
@Aspect
@ConfigurationProperties
public class ValidateAspect {
    private Map<String, String> validateRules = new HashMap<>();

    public Map<String, String> getValidateRules() {
        return validateRules;
    }

    public void setValidateRules(Map<String, String> validateRules) {
        this.validateRules = validateRules;
    }

    @Pointcut("@annotation(cn.dishenghk.wechatgame.Annotaion.ValidateAnnotaion)")
    private void cut() {
    }

    @Before("cut()&&@annotation(validateAnnotaion)")
    public void record(JoinPoint joinPoint, ValidateAnnotaion validateAnnotaion) throws MyException, IOException {
        String valueKeys[] = validateAnnotaion.value();
        Map<String, String> postValues = (Map<String, String>) joinPoint.getArgs()[0];
        for (String key : valueKeys
                ) {
            String rules = this.validateRules.get(key);
            if (rules == null) {
                throw new MyException(500, "不存在验证规则", "不存在验证规则");
            }
            if (!CheckParam.check(postValues.get(key), rules)) {
                throw new MyException(500, "参数验证不同过", this.generateError(key, rules));
            }
        }
    }

    private String generateError(String key, String rules) {
        return "the key '" + key + "' need conformity the rule:'" + rules + "'";
    }

}

4.增加统一自定义错误拦截

@ControllerAdvice
public class WebExceptionHanlder {
    @ResponseBody
    @ExceptionHandler(MyException.class)
    public Response handler(MyException e){
        Response response=new Response();
        response.setMessage(e.getMsg());
        response.setStatus_code(e.getCode());
        response.setData(e.getData());
        return  response;
    }
}

5.在控制器上方法上使用

   
    @RequestMapping("/login")
    @ValidateAnnotaion({"code"})
    public Response login(@RequestBody Map<String,String> data) {

6. 测试

image

todo

  • [ ] 更多传参方式的支持
  • [ ] 字段的多校验格式 实现例如 required|number| 或 min:10|max:20 等多校验
  • [ ] 返回错误的完整性

相关文章

网友评论

      本文标题:利用aop 实现spring boot restful cont

      本文链接:https://www.haomeiwen.com/subject/vscyuqtx.html