athrunwang

          紀元
          數據加載中……
          Java驗證碼

          Java生成驗證碼圖片 
          1.Servlet生成驗證碼圖片

            1 package com.logcd.servlet;
          2
          3 import java.awt.Color;
          4 import java.awt.Font;
          5 import java.awt.Graphics2D;
          6 import java.awt.image.BufferedImage;
          7 import java.util.Random;
          8 import javax.imageio.ImageIO;
          9 import javax.servlet.*;
          10 import java.io.*;
          11 import javax.servlet.http.*;
          12 import javax.servlet.ServletException;
          13 import javax.servlet.http.HttpServlet;
          14 import javax.servlet.http.HttpServletRequest;
          15 import javax.servlet.http.HttpServletResponse;
          16
          17 @SuppressWarnings("serial")
          18 public class RandomCode extends HttpServlet {
          19
          20 public void doGet(HttpServletRequest request, HttpServletResponse response)
          21 throws ServletException, IOException {
          22
          23 this.doPost(request, response);
          24 }
          25
          26 public void doPost(HttpServletRequest request, HttpServletResponse response)
          27 throws ServletException, IOException {
          28
          29 // 驗證碼圖片的寬度。
          30 int width = 70;
          31 // 驗證碼圖片的高度。
          32 int height = 30;
          33 BufferedImage buffImg = new BufferedImage(width, height,
          34 BufferedImage.TYPE_INT_RGB);
          35 Graphics2D g = buffImg.createGraphics();
          36
          37 // 創建一個隨機數生成器類。
          38 Random random = new Random();
          39
          40 // 設定圖像背景色(因為是做背景,所以偏淡)
          41 g.setColor(getRandColor(200, 250));
          42 g.fillRect(0, 0, width, height);
          43 // 創建字體,字體的大小應該根據圖片的高度來定。
          44 Font font = new Font("Times New Roman", Font.HANGING_BASELINE, 28);
          45 // 設置字體。
          46 g.setFont(font);
          47
          48 // 畫邊框。
          49 g.setColor(Color.BLACK);
          50 g.drawRect(0, 0, width - 1, height - 1);
          51 // 隨機產生155條干擾線,使圖象中的認證碼不易被其它程序探測到。
          52 //g.setColor(Color.GRAY);
          53 g.setColor(getRandColor(160,200));
          54 for (int i = 0; i < 155; i++) {
          55 int x = random.nextInt(width);
          56 int y = random.nextInt(height);
          57 int xl = random.nextInt(12);
          58 int yl = random.nextInt(12);
          59 g.drawLine(x, y, x + xl, y + yl);
          60 }
          61
          62 // randomCode用于保存隨機產生的驗證碼,以便用戶登錄后進行驗證。
          63 StringBuffer randomCode = new StringBuffer();
          64
          65 // 設置默認生成4個驗證碼
          66 int length = 4;
          67 // 設置備選驗證碼:包括"a-z"和數字"0-9"
          68 String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
          69
          70 int size = base.length();
          71
          72 // 隨機產生4位數字的驗證碼。
          73 for (int i = 0; i < length; i++) {
          74 // 得到隨機產生的驗證碼數字。
          75 int start = random.nextInt(size);
          76 String strRand = base.substring(start, start + 1);
          77
          78 // 用隨機產生的顏色將驗證碼繪制到圖像中。
          79 // 生成隨機顏色(因為是做前景,所以偏深)
          80 //g.setColor(getRandColor(1, 100));
          81
          82 //調用函數出來的顏色相同,可能是因為種子太接近,所以只能直接生成
          83 g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
          84
          85 g.drawString(strRand, 15 * i + 6, 24);
          86
          87 // 將產生的四個隨機數組合在一起。
          88 randomCode.append(strRand);
          89 }
          90 // 將四位數字的驗證碼保存到Session中。
          91 HttpSession session = request.getSession();
          92 session.setAttribute("rand", randomCode.toString());
          93
          94 //圖象生效
          95 g.dispose();
          96
          97 // 禁止圖像緩存。
          98 response.setHeader("Pragma", "no-cache");
          99 response.setHeader("Cache-Control", "no-cache");
          100 response.setDateHeader("Expires", 0);
          101
          102 response.setContentType("image/jpeg");
          103
          104 // 將圖像輸出到Servlet輸出流中。
          105 ServletOutputStream sos = response.getOutputStream();
          106 ImageIO.write(buffImg, "jpeg", sos);
          107 sos.flush();
          108 sos.close();
          109
          110 }
          111
          112 Color getRandColor(int fc, int bc) {// 給定范圍獲得隨機顏色
          113 Random random = new Random();
          114 if (fc > 255)
          115 fc = 255;
          116 if (bc > 255)
          117 bc = 255;
          118 int r = fc + random.nextInt(bc - fc);
          119 int g = fc + random.nextInt(bc - fc);
          120 int b = fc + random.nextInt(bc - fc);
          121 return new Color(r, g, b);
          122 }
          123
          124 }

          2.配置

          1     <servlet>
          2 <servlet-name>RandomCode</servlet-name>
          3 <servlet-class>com.logcd.servlet.RandomCode</servlet-class>
          4 </servlet>
          5 <servlet-mapping>
          6 <servlet-name>RandomCode</servlet-name>
          7 <url-pattern>/randomCode</url-pattern>
          8 </servlet-mapping>

          3.調用

           1 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
          2 <meta http-equiv="pragma" content="no-cache"/>
          3 <meta http-equiv="cache-control" content="no-cache"/>
          4 <meta http-equiv="expires" content="0"/>
          5
          6 <iframe src="http://127.0.0.1/js_test/randomCode" id="codeFrame" name="codeFrame" frameborder="no" border="0" marginwidth="0"
          7 marginheight="0" scrolling="no" allowtransparency="yes" height="35" width="102"></iframe>
          8 <a href="javascript:void(0);" onclick="refreshCode();">看不清,換一張</a>
          9 <br>
          10 <span id="codeImg"><img border=0 src="randomCode"></span>
          11 <a href="javascript:void(0);" onclick="reloadCode()">看不清,再換一張</a>

           

           1 function $(id){
          2 return document.getElementById(id);
          3 }
          4
          5 /**刷新iframe**/
          6 function refreshCode(){
          7 window.frames["codeFrame"].location.reload();
          8 }
          9
          10 /**替換圖片**/
          11 function reloadCode(){
          12 $("codeImg").innerHTML = "<img border=0 src='randomCode'>";
          13 }

          posted on 2011-12-06 10:36 AthrunWang 閱讀(2769) 評論(3)  編輯  收藏

          評論

          # re: Java驗證碼 2012-04-06 11:25 DFS

          SDF
            回復  更多評論    

          # re: Java驗證碼 2013-08-08 14:43 e

          erw
            回復  更多評論    

          # re: Java驗證碼 2014-03-18 21:46 最代碼

          我根據你的代碼整理分享了一份代碼:Servlet生成驗證碼圖片
          下載地址:http://www.zuidaima.com/share/1724427578084352.htm
            回復  更多評論    

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 肥东县| 阳东县| 高雄县| 丽水市| 泰宁县| 龙门县| 芒康县| 鄂托克旗| 蓬莱市| 怀来县| 天台县| 灵丘县| 九龙县| 海阳市| 五寨县| 周至县| 黑水县| 临海市| 宁武县| 龙州县| 利川市| 江山市| 行唐县| 石首市| 康保县| 来凤县| 富民县| 佳木斯市| 安陆市| 白沙| 闵行区| 寿宁县| 新昌县| 湛江市| 桃源县| 蚌埠市| 平阳县| 娄烦县| 克山县| 呼和浩特市| 巩义市|