spring資料驗證----自定義註解
阿新 • • 發佈:2019-01-10
<dependency> <groupId>commons-validator</groupId> <artifactId>commons-validator</artifactId> <version>1.4.0</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.1.Final</version> </dependency>
在pom.xml中新增上面兩個依賴
自定義註解如下
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; //參考資源:http://www.coolfancy.com/log/47.html , //參考資源:http://www.oschina.net/code/snippet_811941_14131 //參考資源: http://www.xfocus.net/articles/200508/816.html //參考資源:http://www.symantec.com/connect/articles/detection-sql-injection-and-cross-site-scripting-attacks @Target( { METHOD, FIELD, ANNOTATION_TYPE }) @Retention(RUNTIME) @Constraint(validatedBy = CheckSqlInjectionValidator.class) @Documented public @interface CheckSqlInjection { String message() default "{SQL注入驗證未通過}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class CheckSqlInjectionValidator implements ConstraintValidator<CheckSqlInjection, String> { public void initialize(CheckSqlInjection constraintAnnotation) { } public boolean isValid(String object, ConstraintValidatorContext constraintContext) { if (object == null) { return true; } else { return this.sqlValidate(object); } } // 效驗 protected boolean sqlValidate(String str) { // 統一轉為小寫 str = str.toLowerCase(); // 過濾掉的sql關鍵字,可以手動新增 String badStr = "'exec |execute |insert |select |delete |update |count |drop |chr |mid |master |truncate |" + "char |declare |sitename |net user |xp_cmdshell |like'|create |" + "table |from |grant |use |group_concat |column_name |" + "information_schema.columns|table_schema|union |where |order |by |" + "like "; String[] badStrs = badStr.split("\\|"); for (int i = 0; i < badStrs.length; i++) { if (str.indexOf(badStrs[i]) >= 0) { System.err.println("sql注入驗證未通過:" + str); return false; } } return true; } }