Java注解Annotation 完成驗證

Java注解Annotation用起來很方便,也越來越流行,由于其簡單、簡練且易于使用等特點,很多開發工具都提供了注解功能,不好的地方就是代碼入侵比較嚴重,所以使用的時候要有一定的選擇性。

這篇文章將利用注解,來做一個Bean的數據校驗。

下載

http://download.csdn.net/download/hanghangaidoudou/10139375

項目結構?

定義注解

該注解可以驗證成員屬性是否為空,長度,提供了幾種常見的正則匹配,也可以使用自定義的正則去判斷屬性是否合法,同時可以為該成員提供描述信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package?org.xdemo.validation.annotation;
import?java.lang.annotation.ElementType;
import?java.lang.annotation.Retention;
import?java.lang.annotation.RetentionPolicy;
import?java.lang.annotation.Target;
import?org.xdemo.validation.RegexType;
/**
?*?數據驗證
?*?@author?Goofy
?*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.PARAMETER})
public?@interface?DV?{
?????
????//是否可以為空
????boolean?nullable()?default?false;
?????
????//最大長度
????int?maxLength()?default?0;
?????
????//最小長度
????int?minLength()?default?0;
?????
????//提供幾種常用的正則驗證
????RegexType?regexType()?default?RegexType.NONE;
?????
????//自定義正則驗證
????String?regexExpression()?default?"";
?????
????//參數或者字段描述,這樣能夠顯示友好的異常信息
????String?description()?default?"";
}

注解的解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package?org.xdemo.validation.annotation.support;
import?java.lang.reflect.Field;
import?org.xdemo.validation.RegexType;
import?org.xdemo.validation.annotation.DV;
import?org.xdemo.validation.utils.RegexUtils;
import?org.xdemo.validation.utils.StringUtils;
/**
?*?注解解析
?*?@author?Goofy
?*/
public?class?ValidateService?{
?????
????private?static?DV?dv;
?????
????public?ValidateService()?{
????????super();
????}
?????
????//解析的入口
????public?static?void?valid(Object?object)?throws?Exception{
????????//獲取object的類型
????????Class<??extends?Object>?clazz=object.getClass();
????????//獲取該類型聲明的成員
????????Field[]?fields=clazz.getDeclaredFields();
????????//遍歷屬性
????????for(Field?field:fields){
????????????//對于private私有化的成員變量,通過setAccessible來修改器訪問權限
????????????field.setAccessible(true);
????????????validate(field,object);
????????????//重新設置會私有權限
????????????field.setAccessible(false);
????????}
????}
?????
?????
????public?static?void?validate(Field?field,Object?object)?throws?Exception{
????????String?description;
????????Object?value;
????????//獲取對象的成員的注解信息
????????dv=field.getAnnotation(DV.class);
????????value=field.get(object);
?????????
????????if(dv==null)return;
?????????
????????description=dv.description().equals("")?field.getName():dv.description();
?????????
????????/*************注解解析工作開始******************/
????????if(!dv.nullable()){
????????????if(value==null||StringUtils.isBlank(value.toString())){
????????????????throw?new?Exception(description+"不能為空");
????????????}
????????}
?????????
????????if(value.toString().length()>dv.maxLength()&&dv.maxLength()!=0){
????????????throw?new?Exception(description+"長度不能超過"+dv.maxLength());
????????}
?????????
????????if(value.toString().length()<dv.minLength()&&dv.minLength()!=0){
????????????throw?new?Exception(description+"長度不能小于"+dv.minLength());
????????}
?????????
????????if(dv.regexType()!=RegexType.NONE){
????????????switch?(dv.regexType())?{
????????????????case?NONE:
????????????????????break;
????????????????case?SPECIALCHAR:
????????????????????if(RegexUtils.hasSpecialChar(value.toString())){
????????????????????????throw?new?Exception(description+"不能含有特殊字符");
????????????????????}
????????????????????break;
????????????????case?CHINESE:
????????????????????if(RegexUtils.isChinese2(value.toString())){
????????????????????????throw?new?Exception(description+"不能含有中文字符");
????????????????????}
????????????????????break;
????????????????case?EMAIL:
????????????????????if(!RegexUtils.isEmail(value.toString())){
????????????????????????throw?new?Exception(description+"地址格式不正確");
????????????????????}
????????????????????break;
????????????????case?IP:
????????????????????if(!RegexUtils.isIp(value.toString())){
????????????????????????throw?new?Exception(description+"地址格式不正確");
????????????????????}
????????????????????break;
????????????????case?NUMBER:
????????????????????if(!RegexUtils.isNumber(value.toString())){
????????????????????????throw?new?Exception(description+"不是數字");
????????????????????}
????????????????????break;
????????????????case?PHONENUMBER:
????????????????????if(!RegexUtils.isPhoneNumber(value.toString())){
????????????????????????throw?new?Exception(description+"不是數字");
????????????????????}
????????????????????break;
????????????????default:
????????????????????break;
????????????}
????????}
?????????
????????if(!dv.regexExpression().equals("")){
????????????if(value.toString().matches(dv.regexExpression())){
????????????????throw?new?Exception(description+"格式不正確");
????????????}
????????}
????????/*************注解解析工作結束******************/
????}
}

用到的幾個類

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package?org.xdemo.validation;
/**
?*?常用的數據類型枚舉
?*?@author?Goofy
?*
?*/
public?enum?RegexType?{
?????
????NONE,
????SPECIALCHAR,
????CHINESE,
????EMAIL,
????IP,?
????NUMBER,
????PHONENUMBER;
?????
}

其中正則驗證類和字符串工具類請參考以下鏈接:

  1. SuperUtil之RegexUtils

  2. SuperUtil之StringUtils

使用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package?org.xdemo.validation.test;
import?org.xdemo.validation.RegexType;
import?org.xdemo.validation.annotation.DV;
public?class?User?{
?????
????@DV(description="用戶名",minLength=6,maxLength=32,nullable=false)
????private?String?userName;
?????
????private?String?password;
?????
????@DV(description="郵件地址",nullable=false,regexType=RegexType.EMAIL)
????private?String?email;
?????
?????
????public?User(){}
?????
????public?User(String?userName,?String?password,?String?email)?{
????????super();
????????this.userName?=?userName;
????????this.password?=?password;
????????this.email?=?email;
????}
?????
?????
?????
????public?String?getUserName()?{
????????return?userName;
????}
????public?void?setUserName(String?userName)?{
????????this.userName?=?userName;
????}
????public?String?getPassword()?{
????????return?password;
????}
????public?void?setPassword(String?password)?{
????????this.password?=?password;
????}
????public?String?getEmail()?{
????????return?email;
????}
????public?void?setEmail(String?email)?{
????????this.email?=?email;
????}
}

測試代碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package?org.xdemo.validation.test;
import?org.xdemo.validation.annotation.support.ValidateService;
/**
?*?@author?Goofy
?*/
public?class?Test?{
????public?static?void?main(String[]?args){
????????User?user=new?User("張三",?"xdemo.org",?"252878950@qq.com");
????????try?{
????????????ValidateService.valid(user);
????????}?catch?(Exception?e)?{
????????????e.printStackTrace();
????????}
????????user=new?User("zhangsan","xdemo.org","xxx@");
????????try?{
????????????ValidateService.valid(user);
????????}?catch?(Exception?e)?{
????????????e.printStackTrace();
????????}
????????user=new?User("zhangsan","xdemo.org","");
????????try?{
????????????ValidateService.valid(user);
????????}?catch?(Exception?e)?{
????????????e.printStackTrace();
????????}
????}
}


運行效果


本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/387420.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/387420.shtml
英文地址,請注明出處:http://en.pswp.cn/news/387420.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

隱藏馬爾科夫模型HMM

概率圖模型 HMM 先從一個具體的例子入手,看看我們要解決的實際問題.例子引自wiki.https://en.wikipedia.org/wiki/Hidden_Markov_model Consider two friends, Alice and Bob, who live far apart from each other and who talk together daily over the telephone about what …

常用HQL

進入hive客戶端后&#xff1a; 1、建表&#xff1a; create table page_view(viewTime int, userid bigint,page_url string, referrer_url string,ip string comment IP Address of the User)comment This is the page view tablepartitioned by(dt string, country string)r…

阿里云天池 金融風控訓練營Task1 廣東工業站

Task1 賽題理解 一、學習知識點概要 本次學習先是介紹了賽題的背景和概況&#xff0c;題目以金融風控中的個人信貸為背景&#xff0c;給所給的47列特征中&#xff0c;根據貸款申請人的數據信息預測其是否有違約的可能&#xff0c;以此判斷是否通過貸款。隨后介紹了比賽中的評…

如何將.crt的ssl證書文件轉換成.pem格式

如何將.crt的ssl證書文件轉換成.pem格式摘自&#xff1a;https://www.landui.com/help/show-8127 2018-07-04 14:55:41 2158次 準備:有一臺安裝了php的linux操作系統執行下面的openssl命令即可&#xff1a;openssl x509 -in www.xx.com.crt -out www.xx.com.pem轉載于:https://…

SpringMVC學習記錄--Validator驗證分析

一.基于Validator接口的驗證. 首先創建User實例,并加入幾個屬性 ?12345678910111213141516171819202122232425262728293031323334<code class"hljs cs">public class User {private String username;private String password;private String nickname;public …

NTP時間服務器實現Linux時間同步

在linux下&#xff0c;可以通過自帶的NTP(Network Time Protocol)協議通過網絡使自己的系統保持精確的時間。 什么是NTP&#xff1f; NTP是用來使系統和一個時間源保持時間同步的協議。 在自己管理的網絡中建立至少一臺時間服務器來同步本地時間&#xff0c;這樣可以使得在不同…

阿里云天池 Python訓練營Task1:從變量到異常處理

本學習筆記為阿里云天池龍珠計劃Python訓練營的學習內容&#xff0c;學習鏈接為&#xff1a;https://tianchi.aliyun.com/specials/promotion/aicamppython?spm5176.22758685.J_6770933040.1.6f103da1tESyzu 目錄 一、學習知識點概要 二、學習內容 I.變量、運算符與數據類…

python回收機制

目錄 Python的垃圾回收機制引子:一、什么是垃圾回收機制&#xff1f;二、為什么要用垃圾回收機制&#xff1f;三、垃圾回收機制原理分析1、什么是引用計數&#xff1f;2、引用計數擴展閱讀&#xff1f;&#xff08;折疊&#xff09;Python的垃圾回收機制 引子: 我們定義變量會申…

安裝openssl-devel命令

centos&#xff1a; yum install openssl-devel ubuntu&#xff1a; sudo apt-get install openssl sudo apt-get install libssl-dev

阿里云天池 Python訓練營Task2: Python基礎練習:數據結構大匯總 學習筆記

本學習筆記為阿里云天池龍珠計劃Python訓練營的學習內容&#xff0c;學習鏈接為&#xff1a;https://tianchi.aliyun.com/specials/promotion/aicamppython?spm5176.22758685.J_6770933040.1.6f103da1tESyzu 目錄 一、學習知識點概要 二、學習內容 I.列表&#xff08;list…

windows文件與Linux文件互轉

使用命令 unix2dos filename dos2unix filename

1G.小a的排列(C++)

小a的排列&#xff08;C&#xff09; 點擊做題網站鏈接 題目描述 小a有一個長度為n的排列。定義一段區間是"萌"的&#xff0c;當且僅當把區間中各個數排序后相鄰元素的差為1現在他想知道包含數x,y的長度最小的"萌"區間的左右端點 也就是說&#xff0c;我們…

阿里云天池 Python訓練營Task3: Python基礎進階:從函數到高級魔法方法 學習筆記

本學習筆記為阿里云天池龍珠計劃Python訓練營的學習內容&#xff0c;學習鏈接為&#xff1a;https://tianchi.aliyun.com/specials/promotion/aicamppython?spm5176.22758685.J_6770933040.1.6f103da1tESyzu 目錄 一、學習知識點概要 二、學習內容 I.函數 1.定義自己的函…

C# 獲取句柄程序

這個小程序需要用到系統API&#xff0c;也就是需要用到user32中的三個函數。 第一個&#xff1a;WindowFromPoint 返回一個窗口句柄 第二個&#xff1a;GetWindowText 獲取窗口標題 第三個&#xff1a;GetClassName 獲取類名 當然&#xff0c;最重要的一點就是要引用命名空間…

HBase安裝配置

HBase的安裝配置&#xff1a; 4臺主機&#xff1a;hdp0 hdp1 hdp2 hdp3 hdp0 hdp1 跑HMaster hdp2 hdp3 跑HRegionServer 將HBase解壓之后 1、確保安裝ZooKeeper&#xff1b; 2、修改hbase-env.sh export JAVA_HOME/.../jdk export HBASE_MANAGES_ZKfalse //使用外部的…

python cook讀書筆記第2章字符串和文本

使用多個界定符分割字符串 line asdf fjdk; afed, fjek,asdf, fooimport re# line re.split(r[;,\s]\s*,line)# print(line)# [asdf, fjdk, afed, fjek, asdf, foo]"""當你使用 re.split() 函數時候&#xff0c;需要特別注意的是正則表達式中是否包含一個括號…

centos7安裝oracle12c 一

本文 基本參考了下面這篇文章http://blog.csdn.net/gq5251/article/details/42004035 和http://www.linuxidc.com/Linux/2017-08/146528.htm 但是改正了一些錯誤操作系統:CentOS Linux release 7.2.1511 (Core) oracle: oarcle (12.1.0.2.0) - Standard Edition (SE2)幾點要注…

Bigtable的些許重點

分布式數據庫系統 針對于海量數據&#xff0c;可擴展&#xff0c;高吞吐量&#xff0c;低時延 不支持關系模型 通過row和column進行索引&#xff0c;row和column可以是任意字符串 所存儲的數據也是字符串 Bigtable是一個map&#xff0c;value是array of bytes&#xff0c;通…

阿里云天池 Python訓練營Task4: Python數據分析:從0完成一個數據分析實戰 學習筆記

本學習筆記為阿里云天池龍珠計劃Python訓練營的學習內容&#xff0c;學習鏈接為&#xff1a;https://tianchi.aliyun.com/specials/promotion/aicamppython?spm5176.22758685.J_6770933040.1.6f103da1tESyzu 一、學習知識點概要 本次主要通過阿里云天池的賽題【Python入門系…

JMETER從JSON響應中提取數據

如果你在這里&#xff0c;可能是因為你需要使用JMeter從Json響應中提取變量。 好消息&#xff01;您正在掌握掌握JMeter Json Extractor的權威指南。作為Rest API測試指南的補充&#xff0c;您將學習掌握Json Path Expressions 所需的一切。 我們走吧&#xff01;并且不要驚慌&…