springMVC中使用 JSR-303验证器( Validation 接口 )

在pom.xml,添加validator验证器的依赖

    <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.13.Final</version>
      </dependency>

新建一个Cat类

package com.oukele.model;

import javax.validation.constraints.*;

public class Cat {

    @NotBlank//验证字符串非空
    private String id;//猫的编号

    @NotBlank//验证字符串非空
    private String name;//猫的名字

    @Max(value = 5)//最大年龄
    @Min(value = 1)//最小年龄
    private int age;//猫的年龄

    @Pattern(regexp = "^[0-9]{11}$")//电话的格式
    private String tel;//铲屎官的电话\

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", tel='" + tel + '\'' +
                '}';
    }
}
View Code

后端代码:

package com.oukele.web;

import com.oukele.model.Cat;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;

@Controller
public class CatController {

    /**
     * 请求url:/cat
     * 请求方式:post
     * 接收参数:一个经过字符格式转化的对象,json
     * 返回参数:一个cat对象
     * @Valid 开启验证  @Valid后面跟着某个实体类
     * */
    @RequestMapping(path = "/cat",method = RequestMethod.POST)
    @ResponseBody
    private Cat cat(@Valid @RequestBody Cat cat, BindingResult result){
        return cat;
    }


}

 

前端请求代码:

fetch('/cat', {
    method: 'post',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
        id:' ',
        name:'tom',
        age:0,
        tel:''
    })
}).then(resp => resp.json())
    .then(console.log)
    .catch(console.error);

 

 在后台设置一个断点,当请求成功的时候,将会发现,程序帮我们捕获了三个error,

 

 

这些刚好满足我们刚刚在实体类定义的验证注解。

自定义验证注解

 @CatId  验证猫的编号里面不能有数字

 @CallPhone 验证手机号数为11位

@CatId

package com.oukele.my;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.regex.Pattern;

@Target({ElementType.ANNOTATION_TYPE,ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CatValidator.class)
public @interface CatId {

    String message() default "这只猫的编号太长啦";

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

    Class<? extends Payload>[] payload() default { };
}
class CatValidator implements ConstraintValidator<CatId,String>{

    @Override
    public void initialize(CatId constraintAnnotation) {

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {

        //假设 每只猫的编号都不能有数字
        return  Pattern.matches("[^0-9]",value);
    }
}

@CallPhone

package com.oukele.my;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;
import java.util.regex.Pattern;

@Target({ElementType.ANNOTATION_TYPE , ElementType.METHOD , ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CallPhoneValidator.class)
public @interface CallPhone {

    String message() default "电话号码格式错误...";

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

    Class<? extends Payload>[] payload() default { };
}
class CallPhoneValidator implements ConstraintValidator<CallPhone,String>{

    @Override
    public void initialize(CallPhone constraintAnnotation) {

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {

        return Pattern.matches("^[0-9]{11}$",value);
    }
}

使用上我们自定义的注解

 

前端请求:

fetch('/cat', {
    method: 'post',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
        id: '1234567888',
        name: 'tom',
        tel: '10000000000',
        age:6
    })
}).then(resp => resp.json())
    .then(console.log)
    .catch(console.error);

 结果:

 

(个人笔记,写得很菜,请见谅)

 

posted @ 2018-10-31 16:20  追梦滴小蜗牛  阅读(497)  评论(0编辑  收藏  举报