本文實例為大家分享了springmvc實現驗證碼功能展示的具體代碼,供大家參考,具體內容如下
先看效果圖:
思路:
首先驗證碼是一張圖片,是一張有著隨機字母、數字、圖案等組成的圖片,所以這圖片肯定不是固定不變的,肯定是由后端隨機制造出來的,前端用img的src去不斷訪問這個制造的方法。
第一步:前端頁面編寫
登錄使用的是ajax方法,所以使用的是調用點擊事件進行,驗證碼的圖片放在a標簽中是為了方便點擊變換驗證碼。顯示圖片用的是img的src屬性,因為使用的是spingmvc所以調用后臺方法使用action的方式。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<form> <div id= "login_tip" > 管理員登錄 </div> <div><input type= "text" id= "user_code" name= "user_code" class = "username" placeholder= "請輸入賬號" ></div> <div><input type= "password" id= "user_account" name= "user_account" class = "pwd" placeholder= "請輸入密碼" ></div> <div id= "btn_area" > <input type= "text" id= "verificationcode" name= "verificationcode" placeholder= "請輸入驗證碼" class = "verify" > <a href= "javascript:void(0);" rel= "external nofollow" onclick= "verificationcode()" > <img id= "randcodeimage" alt= "驗證碼" src= "verificationcode/generate.action" width= "100" height= "40" /> </a> </div> <div style= "float:left;" > <input type= "button" name= "button" id= "sub_btn" onclick= "login()" value= "登錄" /> </div> <div id= "verification_code" ><b></b></div> </form> |
第二步:編寫js代碼
因為登錄采用的是ajxa,所以后臺登錄會驗證一些數據,不正確的會返回數據到登錄頁面。這里說明一下,在調用生成驗證碼的方法后面為什么要加一個隨機數,這里的隨機數以及這個隨機數的參數名稱可以隨意寫,后端不做任何操作的,這里是防止瀏覽器對一個相同方法進行調用時取緩存的方法,而點擊圖片或驗證碼輸入錯誤不會自動刷新而改變圖片的問題做處理。
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
|
<script type= "text/javascript" > function login(){ //這是使用ajax的方式提交 $.ajax({ type: 'post' , url: 'uase/query.action' , //data:$('#logininputform').serialize(), data:{ 'user_code' : $( "#user_code" ).val(), 'user_account' :$( "#user_account" ).val(), 'verificationcode' :$( "#verificationcode" ).val(), }, datatype: 'json' , success:function(obj){ var rad = math.floor(math.random() * math.pow( 10 , 8 )); if (obj && obj.success== 'true' ){ window.location.href= 'uase/login.action' ; } else { document.getelementbyid( "verification_code" ). innerhtml =obj.msg; //uuuy是隨便寫的一個參數名稱,后端不會做處理,作用是避免瀏覽器讀取緩存的鏈接 $( "#randcodeimage" ).attr( "src" , "verificationcode/generate.action?uuuy=" +rad); $( "#verificationcode" ).val( "" ).focus(); // 清空并獲得焦點 } } }); } /** *驗證碼刷新 */ function verificationcode(){ var rad = math.floor(math.random() * math.pow( 10 , 8 )); //uuuy是隨便寫的一個參數名稱,后端不會做處理,作用是避免瀏覽器讀取緩存的鏈接 $( "#randcodeimage" ).attr( "src" , "verificationcode/generate.action?uuuy=" +rad); } </script> |
第三步:編寫后臺controller控制類
主方法為verificationcode,里面會用到一些隨機數生產的方法以及一些輔助類,全用用上就可以了,因為我這里用到了可以更改類型的驗證碼,所以用到了一個自己編寫的公共的工具類。
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
|
@requestmapping ( "/verificationcode" ) public class verificationcodecontroller extends httpservlet{ private static final long serialversionuid = 1l; /** * 這里用作存入session的名稱 */ private static final string session_key_of_rand_code = "randcode" ; // todo 要統一常量 /** * */ private static final int count = 200 ; /** * 定義圖形大小(寬) */ private static final int width = 105 ; /** * 定義圖形大小(高) */ private static final int height = 35 ; /** * 干擾線的長度=1.414*linewidth */ private static final int linewidth = 1 ; @requestmapping (value = "/generate" , method = { requestmethod.post, requestmethod.get }) public void verificationcode( httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // 設置頁面不緩存 response.setheader( "pragma" , "no-cache" ); response.setheader( "cache-control" , "no-cache" ); response.setdateheader( "expires" , 0 ); // response.setcontenttype("image/png"); // 在內存中創建圖象 final bufferedimage image = new bufferedimage(width, height, bufferedimage.type_int_rgb); // 獲取圖形上下文 final graphics2d graphics = (graphics2d) image.getgraphics(); // 設定背景顏色 graphics.setcolor(color.white); // ---1.color.white為白色 graphics.fillrect( 0 , 0 , width, height); //填充衍射 // 設定邊框顏色 //graphics.setcolor(getrandcolor(100, 200)); // ---2.這是以數字型來設置顏色,顏色模式是指使用三種基色:紅、綠、藍,通過三種顏色的調整得出其它各種顏色,這三種基色的值范圍為0~255 graphics.drawrect( 0 , 0 , width - 1 , height - 1 ); final random random = new random(); // 隨機產生干擾線,使圖象中的認證碼不易被其它程序探測到 for ( int i = 0 ; i < count; i++) { graphics.setcolor(getrandcolor( 150 , 200 )); // ---3. final int x = random.nextint(width - linewidth - 1 ) + 1 ; // 保證畫在邊框之內 final int y = random.nextint(height - linewidth - 1 ) + 1 ; final int xl = random.nextint(linewidth); final int yl = random.nextint(linewidth); graphics.drawline(x, y, x + xl, y + yl); } // 取隨機產生的認證碼(4位數字) final string resultcode = exctractrandcode(); for ( int i = 0 ; i < resultcode.length(); i++) { // 將認證碼顯示到圖象中,調用函數出來的顏色相同,可能是因為種子太接近,所以只能直接生成 // graphics.setcolor(new color(20 + random.nextint(130), 20 + random // .nextint(130), 20 + random.nextint(130))); // 設置字體顏色 graphics.setcolor(color.black); // 設置字體樣式 //graphics.setfont(new font("arial black", font.italic, 18)); graphics.setfont( new font( "times new roman" , font.bold, 24 )); // 設置字符,字符間距,上邊距 system.out.print(resultcode.charat(i)); graphics.drawstring(string.valueof(resultcode.charat(i)), ( 23 * i) + 8 , 26 ); } system.out.println( "直接輸出:" +resultcode); // 將認證碼存入session request.getsession().setattribute(session_key_of_rand_code, resultcode); // 圖象生效 graphics.dispose(); // 輸出圖象到頁面 imageio.write(image, "jpeg" , response.getoutputstream()); } /** * @return 隨機碼 */ private string exctractrandcode() { final string randcodetype = resourceutil.getrandcodetype(); int randcodelength = integer.parseint(resourceutil.getrandcodelength()); if (randcodetype == null ) { return randcodeimageenum.number_char.generatestr(randcodelength); } else { switch (randcodetype.charat( 0 )) { case '1' : return randcodeimageenum.number_char.generatestr(randcodelength); case '2' : return randcodeimageenum.lower_char.generatestr(randcodelength); case '3' : return randcodeimageenum.upper_char.generatestr(randcodelength); case '4' : return randcodeimageenum.letter_char.generatestr(randcodelength); case '5' : return randcodeimageenum.all_char.generatestr(randcodelength); default : return randcodeimageenum.number_char.generatestr(randcodelength); } } } /** * 描述:根據給定的數字生成不同的顏色 * @param 這是以數字型來設置顏色,顏色模式是指使用三種基色:紅、綠、藍,通過三種顏色的調整得出其它各種顏色,這三種基色的值范圍為0~255 * @param 這是以數字型來設置顏色,顏色模式是指使用三種基色:紅、綠、藍,通過三種顏色的調整得出其它各種顏色,這三種基色的值范圍為0~255 * @return 描述:返回顏色 */ private color getrandcolor( int fc, int bc) { // 取得給定范圍隨機顏色 final random random = new random(); if (fc > 255 ) { fc = 255 ; } if (bc > 255 ) { bc = 255 ; } final int r = fc + random.nextint(bc - fc); final int g = fc + random.nextint(bc - fc); final int b = fc + random.nextint(bc - fc); return new color(r, g, b); } /** * 驗證碼輔助類 */ enum randcodeimageenum { /** * 混合字符串 */ all_char( "0123456789abcdefghijkmnpqrstuvwxyzabcdefghijklmnopqrstuvwxyz" ), // 去除小寫的l和o這個兩個不容易區分的字符; /** * 字符 */ letter_char( "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" ), /** * 小寫字母 */ lower_char( "abcdefghijklmnopqrstuvwxyz" ), /** * 數字 */ number_char( "0123456789" ), /** * 大寫字符 */ upper_char( "abcdefghijklmnopqrstuvwxyz" ); /** * 待生成的字符串 */ private string charstr; /** * @param charstr */ private randcodeimageenum( final string charstr) { this .charstr = charstr; } /** * 生產隨機驗證碼 * * @param codelength * 驗證碼的長度 * @return 驗證碼 */ public string generatestr( final int codelength) { final stringbuffer sb = new stringbuffer(); final random random = new random(); final string soursestr = getcharstr(); for ( int i = 0 ; i < codelength; i++) { sb.append(soursestr.charat(random.nextint(soursestr.length()))); } return sb.tostring(); } /** * @return the {@link #charstr} */ public string getcharstr() { return charstr; } } } |
第四步:編寫公用的工具類
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
|
/** * 項目參數工具類 * */ public class resourceutil { private static final resourcebundle bundle = java.util.resourcebundle.getbundle( "sysconfig" ); /** * 獲取隨機碼的長度 * * @return 隨機碼的長度 */ public static string getrandcodelength() { return bundle.getstring( "randcodelength" ); } /** * 獲取隨機碼的類型 * * @return 隨機碼的類型 */ public static string getrandcodetype() { return bundle.getstring( "randcodetype" ); } } |
第五步:配置sysconfig.properties
1
2
|
randcodelength= 4 randcodetype= 5 |
第六步:到這里就大功告成了,可以試試效果了
原文鏈接:http://blog.csdn.net/qq_35572020/article/details/53033203