1. 程式人生 > >Java 簡單的登錄驗證碼

Java 簡單的登錄驗證碼

tro spa 畫筆 應用 build itl std 通知 方式

  1 驗證碼的作用

  驗證碼是為了區分人與機器,如果沒有驗證碼機制,web網站或者應用會遇到很多問題,具體如下:

  ① 網站容易被暴力登錄攻破密碼,可以制作一個自動程序不斷的嘗試登錄,密碼很容易被破解,系統容易癱瘓;

  ② 黑客可以創建自動程序不斷的註冊賬戶,不斷的發帖,不斷的刷票,消耗服務器資源,產生大量垃圾信息;

  驗證碼分為兩部分:圖片與輸入框

<html><br/>
<image src=‘images/logo1.jpg‘ /><hr/>
<head><br/><title>
登錄</title> <br/><h1> 歡迎登錄</h1></head> <br/> <body> <br/> <form action=‘/LoginValid/LoginVerify‘ method=‘post‘ > 用戶id:<input type=‘text‘ name=‘userid‘ value=‘‘> <br/> 用戶密碼:<input type=‘password‘ name=‘password‘ value=‘‘> <br/> <
br/> 驗證碼:<input type=‘text‘ name=‘inputCode‘ value=‘‘ /> <img src=‘/LoginValid/CreateCode2‘ /><br/> <input type=‘submit‘ value=‘登錄‘ /><br/> </form> </body> <br/> </html>

CreateCode實時生成圖片

 1     private static final int IMG_W=82;
 2     private
static final int IMG_H=25; 3 private static final int NUM_CHS=5; 4 private static char[] chs = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890".toCharArray(); 5 private static Random rand = new Random(); 6 7 public void doGet(HttpServletRequest request, HttpServletResponse response) 8 throws ServletException, IOException { 9 10 //禁止瀏覽器緩存隨機圖片 11 response.setDateHeader("Expires",-1); 12 response.setHeader("Cache-Control", "no-cache"); 13 response.setHeader("Pragma", "no-cache"); 14 15 //通知客戶端以圖片的方式打開發送過去的數據 16 response.setHeader("Content-Type", "image/jpeg"); 17 18 //創建image對象 19 BufferedImage image = new BufferedImage(IMG_W, IMG_H, BufferedImage.TYPE_INT_RGB); 20 Graphics g = image.getGraphics(); 21 22 //驗證碼圖片背景顏色 23 Color co = new Color(200,200,255); 24 g.setColor(co); 25 26 g.fillRect(0, 0, IMG_W, IMG_H); 27 //保存驗證碼字符 28 StringBuilder sb = new StringBuilder(); 29 int index=0; 30 for(int i=0; i<NUM_CHS; i++) 31 { 32 //獲取隨機一個下標 33 index = rand.nextInt(chs.length); 34 //給畫筆隨機一個顏色 35 g.setColor(new Color(rand.nextInt(88),rand.nextInt(210),rand.nextInt(150))); 36 //畫出字符 37 g.drawString(chs[index]+"", 15*i+3, 18); 38 sb.append(chs[index]); 39 } 40 41 //將驗證碼保存至session 42 request.getSession().setAttribute("checkCode", sb.toString()); 43 ImageIO.write(image, "jpg", response.getOutputStream()); 44 }

  驗證用戶輸入的驗證碼與session裏保存的是否一致:

 1     public void doGet(HttpServletRequest request, HttpServletResponse response)
 2             throws ServletException, IOException {
 3 
 4         response.setContentType("text/html;charset=utf-8");
 5         request.setCharacterEncoding("utf-8");
 6         PrintWriter out = response.getWriter();
 7         
 8         HttpSession session = request.getSession();
 9         String seCode = (String)session.getAttribute("checkCode");
10         String inputCode = (String)request.getParameter("inputCode");
11         if(seCode.equals(inputCode))
12         {
13             request.getRequestDispatcher("/Main").forward(request, response);
14         }
15         else
16         {
17             request.getRequestDispatcher("/Err").forward(request, response);
18         }
19 
20     }

Java 簡單的登錄驗證碼