SpringBoot校验参数

开始刚工作的时候使用if else 判断参数,校验.几个月后就被大佬嘲讽了,以后使用的SpringBoot的校验注解,进行校验

javax.validation.Valid
org.springframework.validation.annotation.Validated

  这两个基本校验,在开始controller接受参数的时候将其注解在接受实体上,Validated是Valid是包装版,可以进行组校验

  

    @PostMapping("index")
    public Result index(@RequestBody @Valid User user){
        //service处理
        return new Result(user);
    }

    @PostMapping("/user")
    public Result user(@Validated(value = UserValid.class) User user){
        //service处理
        return new Result(user);
    }

  这里的@Validated还可以分组校验,将其在不同的场合,分组分别校验.这个也很简单,详见: https://blog.csdn.net/wangpeng047/article/details/41726299

  之后在接受实体类上就可以添加其验证注解: 

@Data
public class User {
    @NotNull(groups = {First.class})
    private String email;
    @Length(min = 11,max = 11,message = "手机号格式不正确")
    private String phone;
    @NotNull(message = "name not null",groups = {First.class, Second.class})
    private String name;
    @NotNull(message = "age not null",groups = {First.class, Second.class})
    private Integer age;
}

  有时候,我碰到一个如果校验一个参数失败就不再校验了,直接返回错误信息,做其他的校验就有点多次一举了,所以要完整这项操作需要以下配置:

  

import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.HibernateValidatorConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.bootstrap.ProviderSpecificBootstrap;


@Configuration public class ValidConfig { /** * 校验失败,快速失败 * * @return */ @Bean public Validator validator(){ ProviderSpecificBootstrap<HibernateValidatorConfiguration> hibernateValid = Validation.byProvider(HibernateValidator.class); return hibernateValid.configure() .failFast(true) .buildValidatorFactory() .getValidator(); } }

  基本上,以上方法可以应对大部分场景了...

posted @ 2019-02-18 16:30  孤燕南飞  阅读(160)  评论(0编辑  收藏  举报