相信項目中作一些htttp接口,避免不了要對參數進行校驗,大多數狀況下,其實咱們只是校驗是否爲NULL就能夠了java
默認的版本是6.0.9.Final 使用過程當中NotBlank會顯示紅色,因此這裏講版本下降,這樣就不會顯示紅色了git
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <exclusions> <exclusion> <artifactId>validation-api</artifactId> <groupId>javax.validation</groupId> </exclusion> </exclusions> <!--默認的版本是6.0.9.Final 使用過程當中NotBlank會顯示紅色, 因此這裏講版本下降,這樣就不會顯示紅色了--> <version>4.3.2.Final</version> </dependency> <dependency> <artifactId>validation-api</artifactId> <groupId>javax.validation</groupId> </dependency>
一、若是變量傳入的時候是NULL,則不會校驗 相似於 @AssertTrue @Size(min=, max=) 等github
二、爲了咱們之後方便, 全部校驗屬性必須加組,方便閱讀web
空檢查 @Null 驗證對象是否爲null @NotNull 驗證對象是否不爲null, 沒法查檢長度爲0的字符串 Hibernate @NotEmpty 檢查約束元素是否爲NULL或者是EMPTY. @NotBlank 檢查約束字符串是否是Null還有被Trim的長度是否大於0,只對字符串,且會去掉先後空格. Booelan檢查 @AssertTrue 驗證 Boolean 對象是否爲 true @AssertFalse 驗證 Boolean 對象是否爲 false 長度檢查 @Size(min=, max=) 驗證對象(Array,Collection,Map,String)長度是否在給定的範圍以內 @Length(min=, max=) 驗證字符串的長度 日期檢查 @Past 驗證 Date 和 Calendar 對象是否在當前時間以前 @Future 驗證 Date 和 Calendar 對象是否在當前時間以後 @Pattern(regexp="[1-9]{1,3}", message="數量X: 必須爲正整數,而且0<X<1000") 驗證 String 對象是否符合正則表達式的規則 數值檢查,建議使用在Stirng,Integer類型,不建議使用在int類型上,由於表單值爲「」時沒法轉換爲int,但能夠轉換爲Stirng爲"",Integer爲null @Min 驗證 Number 和 String 對象是否大等於指定的值 @Max 驗證 Number 和 String 對象是否小等於指定的值 @DecimalMax 被標註的值必須不大於約束中指定的最大值. 這個約束的參數是一個經過BigDecimal定義的最大值的字符串表示.小數存在精度 @DecimalMin 被標註的值必須不小於約束中指定的最小值. 這個約束的參數是一個經過BigDecimal定義的最小值的字符串表示.小數存在精度 @Digits(integer=,fraction=) 驗證字符串是不是符合指定格式的數字,interger指定整數精度,fraction指定小數精度。 Hibernate @Range(min=10000,max=50000,message="range.bean.wage") @Valid 對象傳遞參數的時候用到 public String doAdd(Model model, @Valid AnimalForm form, BindingResult result){} 其中 Hibernate Validator 附加的 constraint (也就是說若是下面的內容中,不引入hibernate包就不會起做用) @NotBlank 檢查約束字符串是否是Null還有被Trim的長度是否大於0,只對字符串,且會去掉先後空格. @Email 驗證是不是郵件地址,若是爲null,不進行驗證,算經過驗證。 @Length(min=, max=) 驗證字符串的長度 @NotEmpty 被註釋的字符串的必須非空 @Range(min=,max=,message=) 被註釋的元素必須在合適的範圍內
@Configuration public class ValidatorConfiguration { @Bean public MethodValidationPostProcessor methodValidationPostProcessor() { MethodValidationPostProcessor processor = new MethodValidationPostProcessor(); processor.setValidator(validator()); return processor; } @Bean public static Validator validator() { return ValidateUtils.validator; } }
package com.hlj.vialidate.data; import com.hlj.vialidate.ValidateGroup; import com.hlj.vialidate.inter.NameInclude; import lombok.Data; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Range; import javax.validation.Valid; import javax.validation.constraints.*; import java.util.List; /** * @author HealerJean * @version 1.0v * @Description * 注意點 * 一、 下面出了判斷空的註解以外,必須有值纔回校驗 * 二、 全部校驗屬性必須加組,方便閱讀 * @ClassName JavaBean * @date 2019/4/17 14:08. */ @Data public class JavaBean extends BaseBean{ @NotBlank(message = "name 爲空 ",groups = ValidateGroup.HealerJean.class) @Size(min = 1,max = 5,message = "name @Size(min = 1,max = 5 字符串長度 最低爲1 最大爲5",groups = ValidateGroup.HealerJean.class) private String name ; @Size(min = 1,max = 2, message = "list @Size(min = 1,max = 2 集合大小 最低爲1 最大爲2",groups = ValidateGroup.HealerJean.class) private List<String> list; @Length(min = 1,max = 5,message = "@Length(min = 1,max = 5 字符串長度 最低爲1 最大爲5",groups = ValidateGroup.HealerJean.class) private String strLength; @Min(value = 5, message = "strNum @Min(value = 5,message = 字符串(數字的字符串大小判斷)【數字類型的變量均可以】",groups = ValidateGroup.HealerJean.class) private String strNum ; @Range(min = 1,max = 10 ,message = "strRange @Range(min = 1,max = 10 最小爲1,最大爲10 ",groups = ValidateGroup.HealerJean.class) private String strRange ; @DecimalMin(value = "100.1",message = "小數值的判斷,最小爲 100.1",groups = ValidateGroup.HealerJean.class) private String strDecimal ; @Digits(integer = 2,fraction = 2,message = "strDigts @Digits(integer = 2,fraction = 2 整數最高2位,小數最高2位",groups = ValidateGroup.HealerJean.class) private String strDigts; @AssertFalse(message = " @AssertFalse 必須爲false " ,groups = ValidateGroup.HealerJean.class) private Boolean assertFalse ; /** * 內部對象校驗 */ @Valid @NotNull(message = "內部對象不能爲空" ,groups = ValidateGroup.HealerJean.class) private InnerBean innerBean ; /** * 自定義註解校驗 */ @NameInclude(message = "類型必須是type value必須是HealerJean" ,type = "Mail",groups = {ValidateGroup.HealerJean.class}) private String myName ; }
package com.hlj.vialidate.data; import com.hlj.vialidate.ValidateGroup; import lombok.Data; import org.hibernate.validator.constraints.NotBlank; /** * @author HealerJean * @version 1.0v * @ClassName BaseBean * @date 2019/6/11 16:38. * @Description */ @Data public class BaseBean { @NotBlank(message = "父類String 不能爲空",groups = ValidateGroup.HealerJean.class) private String fatherString; }
package com.hlj.vialidate.data; import com.hlj.vialidate.ValidateGroup; import lombok.Data; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotBlank; /** * @author HealerJean * @version 1.0v * @ClassName InnerBean * @date 2019/6/11 16:39. * @Description */ @Data public class InnerBean { @NotBlank(message = "innerBean不能爲空",groups = ValidateGroup.HealerJean.class) @Length(max = 2,message = "innerNname 長度最長爲2",groups = ValidateGroup.HealerJean.class) private String innerNname ; }
package com.hlj.utils; import com.hlj.data.general.AppException; import org.hibernate.validator.HibernateValidator; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import java.util.Set; /** * @Description 校驗工具 */ public class ValidateUtils { public static Validator validator; static { validator = Validation .byProvider(HibernateValidator.class) .configure() //快速返回模式,有一個驗證失敗當即返回錯誤信息 .failFast(true) .buildValidatorFactory() .getValidator(); } /** * 靜態方法校驗使用的 * * @param object * @return */ public static String validate(Object object) { if(object == null){ throw new AppException("參數不完整"); } Set<ConstraintViolation<Object>> validate = validator.validate(object); return resultValidate(validate); } /** * 靜態方法校驗使用,而且帶分組的 * * @param object * @param group * @return */ public static String validate(Object object, Class group) { if (group == null) { return validate(object); } else { Set<ConstraintViolation<Object>> validate = validator.validate(object, group); return resultValidate(validate); } } private static String resultValidate(Set<ConstraintViolation<Object>> validate) { if (!validate.isEmpty()) { final StringBuffer stringBuffer = new StringBuffer(); validate.stream().forEach( item -> stringBuffer.append(item.getMessage()).append(",")); stringBuffer.setLength(stringBuffer.length() - 1); return stringBuffer.toString(); } return "success"; } }
package com.hlj.vialidate; /** * @author HealerJean * @version 1.0v * @Description * @ClassName CoreValidateGroup * @date 2019/4/17 9:30. */ public class ValidateGroup { public interface HealerJean {}; }
package com.hlj.moudle.validate; import com.hlj.data.general.ResponseBean; import com.hlj.utils.ValidateUtils; import com.hlj.vialidate.data.JavaBean; import com.hlj.vialidate.ValidateGroup; import io.swagger.annotations.*; import lombok.extern.slf4j.Slf4j; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; /** * @Description * @Author HealerJean * @Date 2018/3/22 上午10:22. */ @ApiResponses(value = { @ApiResponse(code = 200, message = "訪問正常"), @ApiResponse(code = 301, message = "邏輯錯誤"), @ApiResponse(code = 500, message = "系統錯誤"), @ApiResponse(code = 401, message = "未認證"), @ApiResponse(code = 403, message = "禁止訪問"), @ApiResponse(code = 404, message = "url錯誤") }) @Api(description = "demo控制器") @Controller @RequestMapping("hlj") @Slf4j public class VialidateController { @ApiOperation(value = "Post接口", notes = "Post接口", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE, response = ResponseBean.class ) @PostMapping( value = "validate",produces="application/json;charset=utf-8") @ResponseBody public ResponseBean post(@RequestBody JavaBean JavaBean){ String validate = ValidateUtils.validate(JavaBean,ValidateGroup.HealerJean.class); if(!"success".equals(validate)){ log.info("錯誤信息:{}", validate); } return ResponseBean.buildSuccess(validate); } }
POST http://localhost:8888/hlj/validate Content-Type: application/json; charset=UTF-8 { "name":"1234", "strLength":"12345", "list": ["list","list2"], "strNum":"6", "strRange":"9", "strDecimal":"100.2", "strDigts":"15.66", "fatherString":"fatherString", "innerBean":{ "innerNname":"in" }, }
能夠用於字典校驗正則表達式
import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.*; /** * 自定義註解 */ @Constraint(validatedBy = {NameIncludeValidator.class}) @Documented @Target( { ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface NameInclude { String message() ; //報錯返回的信息 Class<?>[] groups() default { }; //被哪一個組校驗 String type() ; //本身定義的 Class<? extends Payload>[] payload() default { }; }
package com.hlj.vialidate.inter; import org.apache.commons.lang3.StringUtils; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; /** * 校驗數據 */ public class NameIncludeValidator implements ConstraintValidator<NameInclude, String> { private String type; /** * 獲取註解中的值 * @param constraintAnnotation */ @Override public void initialize(NameInclude constraintAnnotation) { type = constraintAnnotation.type(); } /** * @param value 字段數據 * @param context * @return */ @Override public boolean isValid(String value, ConstraintValidatorContext context) { if(StringUtils.isBlank(value)){ return true; } if("Mail".equals(type)&&"HealerJean".equals(value)){ return true ; }else { return false ; } } }
/** * 自定義註解校驗 */ @NameInclude(message = "類型必須是type value必須是HealerJean" ,type = "Mail",groups = {ValidateGroup.HealerJean.class}) @NotNull(message = "自定義校驗不能爲空",groups = {ValidateGroup.HealerJean.class}) private String myName ;
POST http://localhost:8888/hlj/validate Content-Type: application/json; charset=UTF-8 { "name":"1234", "strLength":"12345", "list": ["list","list2"], "strNum":"6", "strRange":"9", "strDecimal":"100.2", "strDigts":"15.66", "fatherString":"fatherString", "innerBean":{ "innerNname":"in" }, "myName":"HealerJean" }
哈,博主很樂意和各路好友交流,若是滿意,請打賞博主任意金額,感興趣的在微信轉帳的時候,備註您的微信或者其餘聯繫方式。添加博主微信哦。spring
請下方留言吧。可與博主自由討論哦apache
微信 | 微信公衆號 | 支付寶 |
---|---|---|