後臺參數驗證

之前在處理web請求參數校驗時,少不了相似下方的代碼java

if(age < 18) {
	System.out.println("請輸入正確的年齡(過小了)");
}
if(age > 100) {
	System.out.println("請輸入正確的年齡(太大了)");
}

if(name == null || name.trim().length()  == 0) {
	System.out.println("姓名不能未空");
}
if(name != null && (name.trim().length() < 2 || name.trim().length() > 20)) {
	System.out.println("姓名長度錯誤");
}

 

能夠用validation插件作,須要引入依賴:web

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

<dependency> 
  <groupId>org.glassfish</groupId> 
  <artifactId>javax.el</artifactId> 
  <version>3.0.0</version> 
</dependency>


所有代碼以下:ui

package test;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.constraints.*;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class ValidateTest {

    public static void main(String[] args) {
        UserInfo user = new UserInfo(0, "", "", null, "s");
        System.out.println("---------- old method ----------");
        oldMethod(user);
        System.out.println("---------- new method ----------");
        newMethod(user);
    }

    private static void oldMethod(UserInfo user) {
        String name = user.getName();
        int age = user.getAge();
        List<String> tags = user.getTags();

        if(age < 18) {
            System.out.println("請輸入正確的年齡(過小了)");
        }
        if(age > 100) {
            System.out.println("請輸入正確的年齡(太大了)");
        }

        if(name == null || name.trim().length()  == 0) {
            System.out.println("姓名不能未空");
        }
        if(name != null && (name.trim().length() < 2 || name.trim().length() > 20)) {
            System.out.println("姓名長度錯誤");
        }

        if(tags.size() < 1 || tags.size() > 10) {
            System.out.println("至少輸入一個標籤,最大支持10個標籤");
        }

        for(String tag : tags) {
            if(tag == null || tag.trim().length()  == 0) {
                System.out.println("標籤內容不能爲空");
            }
        }
    }

    private static void newMethod(UserInfo user) {

        Set<ConstraintViolation<UserInfo>> errorSet = Validation.buildDefaultValidatorFactory().getValidator().validate(user);

        errorSet.forEach(item-> {
            System.out.println(item.getMessage());
        });
    }

    static class UserInfo {

        @Min(value = 18, message = "請輸入正確的年齡(過小了)")
        @Max(value = 100, message = "請輸入正確的年齡(太大了)")
        int age;

//        @Pattern(regexp = "[a-z]|[A-Z]")
        @NotBlank(message = "姓名不能爲空")
        @Size(min = 2, max = 20, message = "姓名長度錯誤")
        String name;

        @NotNull
        @Size(min = 1, max = 10, message = "至少輸入一個標籤,最大支持10個標籤")
        List< @NotBlank(message = "標籤內容不能爲空") @Size(min = 1, max = 10, message = "標籤內容長度限制1-10個字符") String> tags;


        public UserInfo(int age, String name, String... tags) {
            this.age = age;
            this.name = name;
            this.tags = Arrays.asList(tags);
        }

        public int getAge() {
            return age;
        }

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

        public String getName() {
            return name;
        }

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

        public List<String> getTags() {
            return tags;
        }

        public void setTags(List<String> tags) {
            this.tags = tags;
        }
    }

}

新舊方法對比發現,新的方法更加靈活、簡潔、易於維護this

相關文章
相關標籤/搜索