java實現驗證碼

   在開發的系統如果需要使用在外網的,特別要注意有安全措施。驗證碼就是實現安全常見辦法之一,它能防止利用程序對系統進行惡意刷新和自動註冊。

 但是隨着破解技術加強,簡單的註冊碼很難有用。
 
 以下只是實現簡單驗證碼的java代碼
 package com.song.test;
 import java.awt.Color;
  import java.awt.Font;
  import java.awt.Graphics2D;
  import java.awt.p_w_picpath.BufferedImage;
  import java.io.IOException;
  import java.util.Random;
 import javax.p_w_picpathio.ImageIO;
  import javax.servlet.ServletException;
  import javax.servlet.ServletOutputStream;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import javax.servlet.http.HttpSession;
 
 /**
 * @Copyright @ 2009 All right reserved
 * @version 創建時間:Created on Apr 15, 2009
 * @author 作者:Create by www.360buyli.com
 * @description 實現簡單的驗證碼
 */
 
  public class RandomCode extends HttpServlet {
  private static final long serialVersionUID = 1L;
         
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
               throws ServletException, IOException { 
     
           this.doPost(request, response); 
       } 
     
       public void doPost(HttpServletRequest request, HttpServletResponse response) 
               throws ServletException, IOException { 
     
           // 驗證碼圖片的寬度。 
           int width = 70; 
           // 驗證碼圖片的高度。 
           int height = 30; 
           BufferedImage buffImg = new BufferedImage(width, height, 
                   BufferedImage.TYPE_INT_RGB); 
           Graphics2D g = buffImg.createGraphics(); 
     
           // 創建一個隨機數生成器類。 
           Random random = new Random(); 
     
           // 設定圖像背景色(因爲是做背景,所以偏淡) 
           g.setColor(getRandColor(200, 250)); 
           g.fillRect(0, 0, width, height); 
           // 創建字體,字體的大小應該根據圖片的高度來定。 
           Font font = new Font("Times New Roman", Font.HANGING_BASELINE, 28); 
           // 設置字體。 
           g.setFont(font); 
     
           // 畫邊框。 
           g.setColor(Color.BLACK); 
           g.drawRect(0, 0, width - 1, height - 1); 
           // 隨機產生155條幹擾線,使圖象中的認證碼不易被其它程序探測到。 
           //g.setColor(Color.GRAY); 
           g.setColor(getRandColor(160,200)); 
           for (int i = 0; i < 155; i++) { 
               int x = random.nextInt(width); 
               int y = random.nextInt(height); 
               int xl = random.nextInt(12); 
               int yl = random.nextInt(12); 
               g.drawLine(x, y, x + xl, y + yl); 
           } 
     
           // randomCode用於保存隨機產生的驗證碼,以便用戶登錄後進行驗證。 
           StringBuffer randomCode = new StringBuffer(); 
     
           // 設置默認生成4個驗證碼 
           int length = 4; 
           // 設置備選驗證碼:包括"a-z"和數字"0-9" 
           String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 
     
           int size = base.length(); 
     
           // 隨機產生4位數字的驗證碼。 
           for (int i = 0; i < length; i++) { 
               // 得到隨機產生的驗證碼數字。 
               int start = random.nextInt(size); 
               String strRand = base.substring(start, start + 1); 
     
               // 用隨機產生的顏色將驗證碼繪製到圖像中。 
               // 生成隨機顏色(因爲是做前景,所以偏深) 
               //g.setColor(getRandColor(1, 100)); 
                 
               //調用函數出來的顏色相同,可能是因爲種子太接近,所以只能直接生成 
               g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110))); 
     
               g.drawString(strRand, 15 * i + 6, 24); 
     
               // 將產生的四個隨機數組合在一起。 
               randomCode.append(strRand); 
           } 
           // 將四位數字的驗證碼保存到Session中。 
           HttpSession session = request.getSession(); 
           session.setAttribute("rand", randomCode.toString()); 
     
           //圖象生效 
           g.dispose(); 
     
           // 禁止圖像緩存。 
           response.setHeader("Pragma", "no-cache"); 
           response.setHeader("Cache-Control", "no-cache"); 
           response.setDateHeader("Expires", 0); 
     
           response.setContentType("p_w_picpath/jpeg"); 
     
           // 將圖像輸出到Servlet輸出流中。 
           ServletOutputStream sos = response.getOutputStream(); 
           ImageIO.write(buffImg, "jpeg", sos); 
           sos.flush(); 
           sos.close(); 
     
       } 
     
       Color getRandColor(int fc, int bc) {// 給定範圍獲得隨機顏色 
           Random random = new Random(); 
           if (fc > 255) 
               fc = 255; 
           if (bc > 255) 
               bc = 255; 
           int r = fc + random.nextInt(bc - fc); 
           int g = fc + random.nextInt(bc - fc); 
           int b = fc + random.nextInt(bc - fc); 
           return new Color(r, g, b); 
       }
 
 }
 
 web.xml
 
 <servlet>
      <description></description>
      <display-name>RandomCode</display-name>
      <servlet-name>RandomCode</servlet-name>
      <servlet-class>com.song.test.RandomCode</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>RandomCode</servlet-name>
      <url-pattern>/RandomCode</url-pattern>
  </servlet-mapping>
 
 html:
 
 <body>
  <script type="text/javascript">
 
 /**刷新iframe**/
  function refreshCode(){
      window.frames["codeFrame"].location.reload();
  }
 
 /**替換圖片,經測試在firefox下必須使用Math.random();**/
  function reloadCode(){
 
 document.getElementById("imgvcode").src = "http://127.0.0.1/js_test/RandomCode?rc="+Math.random();
  }
 
 </script>
 
 <iframe src="http://127.0.0.1/js_test/RandomCode" id="codeFrame" name="codeFrame" frameborder="no" border="0" marginwidth="0"
  marginheight="0" scrolling="no" allowtransparency="yes" height="35" width="102"></iframe>
  <a href="#" onclick="refreshCode();">看不清,換一張</a>
  <br> 
 <span id="codeImg"><img border=0 src="http://127.0.0.1/js_test/RandomCode"></span>
  <a href="#" onclick="reloadCode();">看不清,再換一張</a>
 
 </body>
  
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章