后臺Java代碼【驗證碼生成】
1
2
3
4
5
6
7
8
9
10
11
|
/** * 隨機生成6位隨機驗證碼 */ public static String createRandomVcode(){ //驗證碼 String vcode = "" ; for ( int i = 0 ; i < 6 ; i++) { vcode = vcode + ( int )(Math.random() * 9 ); } return vcode; } |
后臺Java代碼【使用驗證碼并將驗證碼保存到session里面】
1
2
3
|
String authCode = xioo.createRandomVcode(); //隨機生成驗證碼 HttpSession session=request.getSession(); //session屬性 session.setAttribute( "authCode" , authCode); // 保存驗證碼到session里面 |
后臺Java代碼【將用戶輸入的驗證碼與session里面的驗證碼對比】
1
2
3
4
5
6
7
8
9
10
11
12
|
HttpSession session=request.getSession(); String usercode=request.getParameter( "user_code" ); //獲取用戶輸入的驗證碼 String sessioncode=(String) session.getAttribute( "authCode" ); //獲取保存在session里面的驗證碼 String result= "" ; if ( usercode != null && usercode.equals(sessioncode)){ //對比兩個code是否正確 result = "1" ; } else { result = "0" ; } PrintWriter out = response.getWriter(); out.write(result.toString()); //將數據傳到前臺 } |
前臺Ajax代碼【獲取用戶輸入的代碼傳到后臺】
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
$(document).ready(function() { $( "#user_code" ).blur(function() { var user_code = $( "#user_code" ).val(); //ur事件 // 向后臺發送處理數據 $.ajax({ url : "CheckCode" , //目標地址 data : "user_code=" + user_code, //傳輸的數據 type : "POST" , // 用POST方式傳輸 dataType : "text" , // 數據格式 success : function(data) { data = parseInt(data, 10 ); if (data == 1 ) { $( "#error" ).html( "<font color='#339933'>√ 短信驗證碼正確,請繼續</font>" ); } else if (data == 0 ){ $( "#error" ).html( "<font color='red'>× 驗證碼有誤,請核實后重新填寫</font>" ); } } }); }); }); |
<input type="text" name="user_code" id="user_code" placeholder="請輸入驗證碼"/>
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持服務器之家!
原文鏈接:http://www.cnblogs.com/BobCoder/p/6421593.html