Springboot之自定义参数验证

针对表单提交时,我们需要对参数进行校验,然而验证的种类不能符合我们的需求,需要自定义参数验证。

自定义参数验证依赖注解实现,所有我们需要自定义一个自己的注解

手机号的验证注解

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = PhoneValidator.class)
public @interface Phone {

    boolean required() default true;
	// 这个地方修改错误提示字符,其他地方不要修改
    String message() default "手机号码格式错误";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };

}

接着实现参数验证的类

import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * 手机号验证的实现类
 * @author molong
 * @date 2018/1/26
 */
public class PhoneValidator implements ConstraintValidator<Phone, String> {

    private boolean required = false;
	// 定义的手机号验证正则表达式
    private Pattern pattern = Pattern.compile("1(([38]\\d)|(5[^4&&\\d])
                                |(4[579])|(7[0135678]))\\d{8}");

    @Override
    public void initialize(Phone constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext
                             constraintValidatorContext) {

        if(required) {
            return pattern.matcher(s).matches();
        }else {
            if(StringUtils.isEmpty(s)) {
                return false;
            }else{
                return pattern.matcher(s).matches();
            }
        }
    }
}

在实体类上添加

public class Login {

    @NotNull
    @Phone
    private String mobile;

    @NotNull
    @Length(min=12)
    private String password;

    // ... set/get省略
}

当发送Post请求的时候

@PostMapping("/login")
public Object login(@Valid Login login) {
    System.out.println(login);
    // 省略...,只做测试
    return login;
}

返回的json字符串

{
    "timestamp": "2019-01-26T10:28:16.400+0000",
    "status": 400,
    "error": "Bad Request",
    "errors": [
        {
            "codes": [
                "Length.login.password",
                "Length.password",
                "Length.java.lang.String",
                "Length"
            ],
            "arguments": [
                {
                    "codes": [
                        "login.password",
                        "password"
                    ],
                    "arguments": null,
                    "defaultMessage": "password",
                    "code": "password"
                },
                2147483647,
                12
            ],
            "defaultMessage": "长度需要在12和2147483647之间",
            "objectName": "login",
            "field": "password",
            "rejectedValue": "123456",
            "bindingFailure": false,
            "code": "Length"
        },
        {
            "codes": [
                "Phone.login.mobile",
                "Phone.mobile",
                "Phone.java.lang.String",
                "Phone"
            ],
            "arguments": [
                {
                    "codes": [
                        "login.mobile",
                        "mobile"
                    ],
                    "arguments": null,
                    "defaultMessage": "mobile",
                    "code": "mobile"
                },
                true
            ],
            "defaultMessage": "手机号码格式错误",
            "objectName": "login",
            "field": "mobile",
            "rejectedValue": "23445678909",
            "bindingFailure": false,
            "code": "Phone"
        }
    ],
    "message": "Validation failed for object='login'. Error count: 2",
    "path": "/miaosha/login"
}

在 defaultMessage 中就包含了我们定义的错误返回信息。接着我们可以定义全局的异常类对错误进行处理。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值