栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

使用springboot编写自定义参数校验注解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用springboot编写自定义参数校验注解

SpringBoot自定义注解实现参数校验Demo 1. 导入依赖
		
       	
            org.springframework.boot
            spring-boot-starter-validation
        
2.编写检索电话号自定义注解: 2.1:编写测试接口
	@PostMapping("/doLogin")
    @ResponseBody
    public String doLogin(@Valid LoginVo loginVo){
        return "测试成功!";
    }
2.2:编写LoginVo实体
@Data
public class LoginVo {
    @NotNull(message = "电话号不能为空!")//不能为空
    @IsMobile//自定义检索电话号注解
    private String mobile;

    @NotNull//不能为空
    @Length(message = "密码不能为空!")(min = 32)//限制密码最短长度
    private String password;
}
2.3:编写返回vo实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RespBean {
    private long code;//状态码
    private String message;//信息
    private Object data;//数据
	
    public static RespBean success(String msg){
        return new RespBean(200, msg, null);
    }
    
    public static RespBean error(String msg){
        return new RespBean(500, msg, null);
    }
}
2.4:编写@IsMobile注解类
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@documented
@Constraint(validatedBy = {IsMobilevalidator.class})
public @interface IsMobile {

    boolean required() default true;//默认参数为必填

    String message() default "手机号码格式错误!";//如果手机号格式不对则会抛异常

    Class[] groups() default {};

    Class[] payload() default {};

}
2.5:编写手机号校验工具类
public class ValidatorUtil {

    private static final Pattern mobile_pattern = Pattern.compile("[1]([3-9])[0-9]{9}$");

    public static Boolean isMobile(String mobile){
        if (StringUtils.isEmpty(mobile)){//判断电话号是否为空
            return false;
        }
        Matcher matcher = mobile_pattern.matcher(mobile);//使用正则判断
        return matcher.matches();
    }
}
2.6:编写自定义参数检索注解类
public class IsMobilevalidator implements ConstraintValidator {
    private boolean required = false;
    @Override
    public void initialize(IsMobile constraintAnnotation) {
        required = constraintAnnotation.required();//设置参数不能为空
    }
    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (required){//如果参数不为空则判断电话号是否正确
            return ValidatorUtil.isMobile(value);
        }else {
            if (StringUtils.isEmpty(value)){
                return true;
            }else {
                return ValidatorUtil.isMobile(value);
            }
        }
    }
}

前端代码省略。。。

2.8:测试结果:


通过测试控制台会抛出一个BindException异常 接下来编写全局异常捕获。

3.编写全局异常处理
@RestControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(BindException.class)
	public RespBean exceptionHandler(BindException e){
	    if (e instanceof BindException){
	        return RespBean.error(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());//获取注解中message值
	    }
	    return RespBean.error("服务器异常!");
	}
}
3.1:测试结果
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/425251.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号