Fork me on GitHub

springboot使用hibernate validator校验

第一步:设置引用pom.xml文件

 

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>

或者引用

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>spring-boot-starter-web包里面有hibernate-validator包,不需要引用hibernate validator依赖可以查看 hibernate validator 官方文档地址: http://hibernate.org/validator/documentation/第二步骤: 写异常类

 1 package com.hujiang.cctalk.common.exception;
 2 
 3 import com.hujiang.basic.framework.rest.model.DataResult;
 4 import org.springframework.validation.BindingResult;
 5 import org.springframework.web.bind.MethodArgumentNotValidException;
 6 import org.springframework.web.bind.annotation.ControllerAdvice;
 7 import org.springframework.web.bind.annotation.ExceptionHandler;
 8 import org.springframework.web.bind.annotation.ResponseBody;
 9 
10 import java.util.Date;
11 
12 /**
13  * @Description 全局异常处理类
14  * @Auhor lichuanjie
15  * @Date 2018/12/23 下午6:26
16  * @Version 1.0
17  **/
18 @ResponseBody
19 @ControllerAdvice
20 public class CcGlobleExceptionHandler {
21     @ExceptionHandler(value = MethodArgumentNotValidException.class)
22     public DataResult<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
23         BindingResult bindingResult = ex.getBindingResult();
24         DataResult<Object> errorResult = new DataResult<>();
25         errorResult.setStatus(-40001);
26         errorResult.setMessage(bindingResult.getFieldError().getDefaultMessage());
27         errorResult.setTime(new Date());
28         return errorResult;
29     }
30 }
全局异常类

 


第三步骤:请求Request对象设置

   

  1 package com.hujiang.cctalk.marketing.activity.support.model.dto.request.invite;
  2 
  3 import java.util.Date;
  4 import java.util.List;
  5 
  6 import com.hujiang.basic.framework.rest.model.BaseUserRequest;
  7 import lombok.Data;
  8 import org.hibernate.validator.constraints.*;
  9 
 10 import javax.validation.constraints.*;
 11 
 12 
 13 /**
 14  * @author lichuanjie
 15  * @version 1.0
 16  * @created 2018-12-04 16:43:02
 17  */
 18 
 19 @Data
 20 public class ProductInviteCreateRequest extends BaseUserRequest<Integer> {
 21     @NotNull(message = "sellerId不能为空")
 22     private Integer sellerId;
 23 
 24     /**
 25      * 商品ID
 26      **/
 27     @NotNull(message = "商品ID不能为空")
 28     private Long productId;
 29 
 30     /**
 31      * 邀请名称
 32      **/
 33     @NotBlank(message = "邀请码名称不能为空")
 34     @Length(max = 50, message = "邀请码名称不能超过50字符")
 35     private String inviteName;
 36 
 37     /**
 38      * 总共
 39      *
 40      * @Range CharSequence, Collection, Map and Arrays,BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types
 41      **/
 42     @Range(min = 1, max = 10000, message = "邀请码数量必须1-10000")
 43     private Integer total;
 44 
 45     /**
 46      * 过期时间
 47      *
 48      * @Future 限制必须是一个将来的日期
 49      **/
 50     @NotNull(message = "邀请码过期时间不能为空")
 51     @Future(message = "邀请码过期时间必须大于当前时间")
 52     private Date expireDate;
 53     /**
 54      * 来源
 55      *
 56      * @NotBlank 验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格
 57      **/
 58     @NotBlank(message = "inviteSource不能为空")
 59     private String inviteSource;
 60 
 61     /**
 62      * @Past 限制必须是一个过去的日期
 63      */
 64     @Past(message = "验证date和calendar对象是否在当前时间之前")
 65     private Date pastDate;
 66 
 67     /**
 68      * @Max 限制必须为一个不大于指定值的数字<=
 69      */
 70     @Max(value = 100, message = "不能大于100岁!")
 71     private Integer maxAge;
 72 
 73     /**
 74      * @Min验证number和string对象是否大等于指定的值
 75      */
 76     @Min(value = 18, message = "必须年满18岁!")
 77     private Integer minAge;
 78 
 79     @Pattern(regexp = "[a-za-z0-9._%+-]+@[a-za-z0-9.-]+\\.[a-za-z]{2,4}", message = "patternEmail邮件格式错误")
 80     private String patternEmail;
 81 
 82     /**
 83      * @Email 验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式
 84      */
 85     @Email(message = "输入正确的邮箱")
 86     private String email;
 87 
 88     /**
 89      * @NotEmpty 验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)
 90      */
 91     @NotEmpty(message = "userIdList非空")
 92     private List<String> userIdList;
 93 
 94     @URL(message = "输入正确的URL地址")
 95     private String url;
 96 
 97     /**
 98      *
 99      * @Size: String, Collection, Map and arrays. Additionally supported by HV: any sub-type of CharSequence.
100      */
101     @Size(min = 10, max = 20,message = "密码长度必须10-20字符")
102     private String passWord;
103 }
校验Request 类

 

第三步骤:Controller设置
标记:@Validated

1  @RequestMapping(value = "/create", method = RequestMethod.POST)
2     public DataResult<ProductInviteInfoDto> createInvite(@RequestBody @Validated ProductInviteCreateRequest request) {
3         return DataResult.ok(0, "success", productInviteService.createInvite(request));
4     }
Controller

 

第四补充自定义校验注解:

 1 package com.hujiang.cctalk.miaosha.validate;
 2 
 3 import javax.validation.Constraint;
 4 import javax.validation.Payload;
 5 import java.lang.annotation.*;
 6 import static java.lang.annotation.ElementType.*;
 7 import static java.lang.annotation.ElementType.PARAMETER;
 8 import static java.lang.annotation.RetentionPolicy.RUNTIME;
 9 
10 @Target({TYPE, METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })// 约束注解应用的目标元素类型(TYPE   ,METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER等)
11 @Retention(RUNTIME)// 约束注解应用的时机
12 @Documented
13 @Constraint(validatedBy = { IsMobileValidator.class})// 与约束注解关联的验证器
14 public @interface IsMobile {
15 
16     boolean required() default true;//是否校验
17 
18     String message() default "手机号码错误"; // 约束注解验证时的输出消息
19 
20     Class<?>[] groups() default {};// 约束注解在验证时所属的组别
21 
22     Class<? extends Payload>[] payload() default {};// 约束注解的有效负载
23 }
手机号校验注解类接口

 

 1 package com.hujiang.cctalk.miaosha.validate;
 2 import org.thymeleaf.util.StringUtils;
 3 import javax.validation.ConstraintValidator;
 4 import javax.validation.ConstraintValidatorContext;
 5 
 6 public class IsMobileValidator implements ConstraintValidator<IsMobile,String> {
 7 
 8     private boolean required = false;
 9 
10     //初始化方法
11     @Override
12     public void initialize(IsMobile constraintAnnotation) {
13         required = constraintAnnotation.required();
14     }
15 
16     //校验方法
17     @Override
18     public boolean isValid(String value, ConstraintValidatorContext context) {
19         if (required == false) {
20             return ValidatorUtil.isMobile(value);
21         }else {
22             if (StringUtils.isEmpty(value)) {
23                 return true;
24             }
25             return ValidatorUtil.isMobile(value);
26         }
27     }
28 
29 }
手机号校验实现类

 

 1 import org.thymeleaf.util.StringUtils;
 2 import java.util.regex.Matcher;
 3 import java.util.regex.Pattern;
 4  
 5 /**
 6  * 手机号格式校验
 7  */
 8 public class ValidatorUtil {
 9  
10     //手机号格式表达式
11     private static final Pattern mobile_pattern = Pattern.compile("1\\d{10}");
12  
13     /**
14      * 校验src是否为指定的手机号格式
15      * @param src 需要校验的手机号
16      * @return 是指定的手机号返回true,否则false
17      */
18     public static boolean isMobile(String src){
19         if (StringUtils.isEmpty(src)){
20             return false;
21         }
22         Matcher m = mobile_pattern.matcher(src);
23         return m.matches();
24     }
25 }
26 }
校验工具类

 

第五:升级版本:如何设置message 抽离配置文件?可以通过加一个配置类:

 1 package com.hujiang.cctalk.marketing.main;
 2 
 3 import org.springframework.context.MessageSource;
 4 import org.springframework.context.annotation.Bean;
 5 import org.springframework.context.annotation.Configuration;
 6 import org.springframework.context.support.ReloadableResourceBundleMessageSource;
 7 import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
 8 
 9 /**
10  * @Description TODO
11  * @Auhor lichuanjie
12  * @Date 2018/12/29 下午4:28
13  * @Version 1.0
14  **/
15 @Configuration
16 public class BeanValidatorConfig  {
17 
18     @Bean
19     public MessageSource messageSource() {
20         ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
21         messageSource.setBasename("classpath:messages");
22         messageSource.setDefaultEncoding("UTF-8");
23         return messageSource;
24     }
25 
26     @Bean
27     public LocalValidatorFactoryBean validator() {
28         LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
29         bean.setValidationMessageSource(messageSource());
30         return bean;
31     }
32 
33 }
校验配置类

 

项目中增加一个配置文件:
ValidationMessages_zh_CN.properties
内容:
username.message.error=错误英文


 

posted @ 2018-12-23 20:46  会飞的笨石头  阅读(289)  评论(0编辑  收藏  举报