[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. 测试
![](https://img.haomeiwen.com/i4712609/fbfc035009a3dd9b.png)
todo
- [ ] 更多传参方式的支持
- [ ] 字段的多校验格式 实现例如 required|number| 或 min:10|max:20 等多校验
- [ ] 返回错误的完整性
网友评论