很多網站都有該實現
作用:
為了提高系統的安全性
有了驗證碼,我們就可以要求用戶在輸入用戶名,密碼等信息后,同時輸入圖片上的文字,用戶提交后,系統會首先從session中提取剛剛生成的驗證碼,并和用戶輸入的驗證碼進行比較,如果比較相等,表示用戶是從登錄界面登錄過來的,否則,表示用戶是非法的,我們使用驗證碼,是確保系統的使用必須要進行登錄成功之后,才能使用,避免用戶直接在地址欄中輸入要訪問的頁面。
也就是說,使用驗證碼,就強制用戶用戶必須先從登錄界面登錄
二. 驗證實現方式
用到兩個關鍵類,這兩個類跟圖片的輸出是有關系的
1
2
3
4
5
|
BufferedImage im = new BufferedImage( 60 , 20 ,BufferedImage.TYPE_INT_RGB); //第一個參數im表示一個圖片對象 //JPG表示圖片輸出類型 //response.getOutputStream()代表一個響應的輸出流,也就是說,你訪問這個servlet.該servlet就會圖片顯示給你 ImageIO.write(im, "JPG" ,response.getOutputStream()); |
三. 實現步驟
1.使用BufferedImage產生一個圖片,然后使用ImageIO輸出,并指定為JPG格式
1
2
3
4
5
|
BufferedImage im = new BufferedImage( 60 , 20 ,BufferedImage.TYPE_INT_RGB); //第一個參數im表示一個圖片對象 //JPG表示圖片輸出類型 //response.getOutputStream()代表一個響應的輸出流,也就是說,你訪問這個servlet.該servlet就會圖片顯示給你 ImageIO.write(im, "JPG" ,response.getOutputStream()); |
2.獲取圖片繪圖對象
Graphics g = im.getGraphics();
3.填充繪圖區域
1
2
3
4
5
|
Random rm = new Random(); Color c = new Color(rm.nextInt(255),rm.nextInt(255),rm.nextInt(255)); g.setColor(c); //填充整個圖片的顏色 g.fillRect(0, 0, 60, 20); |
4.向圖片中輸出數字
1
2
3
|
g.setColor( new Color(rm.nextInt( 255 ),rm.nextInt( 255 ),rm.nextInt( 255 ))); g.setFont( new Font( "華文隸書" ,Font.BOLD|Font.ITALIC, 28 )); g.drawString( "8" , 1 , 18 ); |
5.隨機4位數字
1
2
3
4
5
6
|
//隨機產生4位數字 for ( int i= 0 ;i< 4 ;i++){ g.setColor( new Color(rm.nextInt( 255 ),rm.nextInt( 255 ),rm.nextInt( 255 ))); g.setFont( new Font( "Gungsuh" ,Font.BOLD|Font.ITALIC, 22 )); g.drawString( "" +rm.nextInt( 10 ), (i* 15 )+ 2 , 18 ); } |
6.隨機產生中文
1
2
3
4
5
6
|
String str = "胸有激雷而面如平湖者可拜上將軍" ; for ( int i= 0 ;i< 4 ;i++){ g.setColor( new Color(rm.nextInt( 255 ),rm.nextInt( 255 ),rm.nextInt( 255 ))); g.setFont( new Font( "Gungsuh" ,Font.BOLD|Font.ITALIC, 15 )); g.drawString( "" +str.charAt(rm.nextInt(str.length())), (i* 15 )+ 2 , 18 ); } |
7.在頁面中如何來引入該驗證碼:
- <img alt="驗證碼" src="/ImageServlet">
8.保存數字,以便進行登錄比較
1
2
|
//將得到的四個數字保存到session中,以便當用戶登錄的時候,用來比較 request.getSession().setAttribute( "piccode" , sbf.toString()); |
9.登錄驗證
首先,需要驗證該用戶在數據庫中是否存在,如果存在,還需要驗證輸入的驗證碼是否一致.
驗證成功后,需要轉發到相關的操作頁面.
代碼實例:
1
2
3
4
5
6
7
8
9
10
11
12
|
boolean b_exist = login.validate(username,passwd); //如果該用戶存在 if (b_exist){ String pic = "" +request.getSession().getAttribute( "piccode" ); //比較驗證碼 if (!pic.equals( "" ) && pic.equals(code)){ //向session中存入用戶信息,以供其他中來使用 request.getSession().setAttribute( "username" , username); response.sendRedirect( "index.jsp" ); } } |
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持服務器之家!
原文鏈接:http://www.cnblogs.com/liu321kai/p/6257131.html