本篇文章主要介紹了java validation 後台參數驗證的使用詳解,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧
一、前言
在後台開發過程中,對參數的校驗成為開發環境不可缺少的一個環節。例如參數不能為null,email那麼必須符合email的格式,如果手動進行if判斷或寫正規表示式判斷無意開發效率太慢,在時間、成本、品質的賽局必然會落後。所以把校驗層抽象化是必然的結果,下面說下幾個解決方案。
二、幾個解決方案
1、struts2的valid可以透過設定xml,xml中描述規則和傳回的訊息,這種方式比較麻煩、開發效率低,不推薦
2、validation bean 是基於JSR-303標準開發出來的,使用註解方式實現,及其方便,但是這只是一個接口,沒有具體實現. Hibernate Validator是一個hibernate獨立的包,可以直接引用,他實現了validation bean同時有做了擴展,比較強大,實現圖如下:
##點此查看中文官方手冊3、oval 是一個可擴展的Java物件資料驗證框架,驗證的規則可以透過設定檔、Annotation、POJOs 進行設定。可以使用純Java 語言、JavaScript 、Groovy 、BeanShell 等進行規則的編寫,本次不過多講解三、bean validation 框架驗證介紹
bean validation 套件放在maven上維護,最新套件的座標如下:<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency>
#
下面開始用程式碼實作一下:#1、定義一個待驗證的bean:Student.javapackage com.shishang; import javax.validation.constraints.*; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; public class Student implements Serializable { @NotNull(message = "名字不能为空") private String name; @Size(min = 6,max = 30,message = "地址应该在6-30字符之间") private String address; @DecimalMax(value = "100.00",message = "体重有些超标哦") @DecimalMin(value = "60.00",message = "多吃点饭吧") private BigDecimal weight; private String friendName; @AssertTrue private Boolean isHaveFriend(){ return friendName != null?true:false; } @Future(message = "生日必须在当前实践之前") private Date birthday; @Pattern(regexp = "^(.+)@(.+)$",message = "邮箱的格式不合法") private String email; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public BigDecimal getWeight() { return weight; } public void setWeight(BigDecimal weight) { this.weight = weight; } public String getFriendName() { return friendName; } public void setFriendName(String friendName) { this.friendName = friendName; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
package com.use; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; public class StudentTest implements Serializable { public static void main(String[] args) { Student xiaoming = getBean(); List<String> validate = validate(xiaoming); validate.forEach(row -> { System.out.println(row.toString()); }); } private static Student getBean() { Student bean = new Student(); bean.setName(null); bean.setAddress("北京"); bean.setBirthday(new Date()); bean.setFriendName(null); bean.setWeight(new BigDecimal(30)); bean.setEmail("xiaogangfan163.com"); return bean; } private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); public static <T> List<String> validate(T t) { Validator validator = factory.getValidator(); Set<ConstraintViolation<T>> constraintViolations = validator.validate(t); List<String> messageList = new ArrayList<>(); for (ConstraintViolation<T> constraintViolation : constraintViolations) { messageList.add(constraintViolation.getMessage()); } return messageList; } }
四、自訂bean validation 註解驗證有時框架自帶的沒法滿足我們的需求,這時就需要自己動手豐衣足食了,恩恩,這個不難,下面說下。
這個範例驗證字串是大寫還是小寫約束標註,程式碼如下:
1、枚舉型別CaseMode, 來表示大寫或小寫模式
package com.defineconstrain; /** * created by xiaogangfan * on 16/10/25. */ public enum CaseMode { UPPER, LOWER; }
#
package com.defineconstrain; /** * created by xiaogangfan * on 16/10/25. */ import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.*; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Target( { METHOD, FIELD, ANNOTATION_TYPE }) @Retention(RUNTIME) @Constraint(validatedBy = CheckCaseValidator.class) @Documented public @interface CheckCase { String message() default "{com.mycompany.constraints.checkcase}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; CaseMode value(); }
#
package com.defineconstrain; /** * created by xiaogangfan * on 16/10/25. */ import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class CheckCaseValidator implements ConstraintValidator<CheckCase, String> { private CaseMode caseMode; public void initialize(CheckCase constraintAnnotation) { this.caseMode = constraintAnnotation.value(); } public boolean isValid(String object, ConstraintValidatorContext constraintContext) { if (object == null) return true; if (caseMode == CaseMode.UPPER) return object.equals(object.toUpperCase()); else return object.equals(object.toLowerCase()); } }
#
@CheckCase(value = CaseMode.LOWER,message = "名字的拼音需要小写") private String spellName;
bean.setSpellName("XIAOGANGFAN");
以上是Java中有關validation後台參數驗證的使用詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!