首页 > 代码库 > 图片验证码

图片验证码

1.jsp页面部分:

            <tr >                <td id="check" colspan="3">验证码:                                 <input id="auth_code" name="Imgcheck" type="text"/>                 <img id="img" src="http://www.mamicode.com/checkimageURL" onclick="changeCode()" style="width: 70px"/>                 (看不清?点图片试试)                </td>            </tr>

2.验证码java文件:

  1 package cn.itcast.oa.utils;  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.io.IOException;  8 import java.util.Random;  9  10 import javax.imageio.ImageIO; 11 import javax.servlet.ServletException; 12 import javax.servlet.ServletOutputStream; 13 import javax.servlet.http.HttpServlet; 14 import javax.servlet.http.HttpServletRequest; 15 import javax.servlet.http.HttpServletResponse; 16 import javax.servlet.http.HttpSession; 17  18 public class CheckImage extends HttpServlet { 19      20     private int x = 0; 21     // 设置验证码图片中显示的字体高度 22     private int fontHeight; 23     private int codeY; 24  25     // 在这里定义了验证码图片的宽度 26     private int width = 60; 27     // 定义验证码图片的高度。 28     private int height = 20; 29     // 定义验证码字符个数,此处设置为4位 30     private int codeNum = 4; 31      32      Color getRandColor(int ff,int cc){ 33          //给定范围获得随机颜色 34          Random random = new Random(); 35          if(ff>255) ff=255; 36          if(cc>255) cc=255; 37          int r=ff+random.nextInt(cc-ff); 38          int g=ff+random.nextInt(cc-ff); 39          int b=ff+random.nextInt(cc-ff); 40          return new Color(r,g,b); 41   } 42  43  44     char[] codes = { ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘, ‘A‘, 45             ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘, ‘G‘, ‘H‘, ‘I‘, ‘J‘, ‘K‘, ‘L‘, ‘M‘, ‘N‘, 46             ‘O‘, ‘P‘, ‘Q‘, ‘R‘, ‘S‘, ‘T‘, ‘U‘, ‘V‘, ‘W‘, ‘X‘, ‘Y‘, ‘Z‘, }; 47  48     /** 49      * 对验证图片属性进行初始化 50      */ 51     public void init() throws ServletException { 52         // 从部署文件web.xml中获取程序初始化信息,图片宽度跟高度,字符个数信息 53         // 获取初始化字符个数 54         String strCodeNums = this.getInitParameter("codeNum"); 55         // 获取验证码图片宽度参数 56         String strW = this.getInitParameter("w"); 57         // 获取验证码图片高度参数 58         String strH = this.getInitParameter("h"); 59  60         // 将配置的字符串信息转换成数值类型数字 61         try { 62             if (strH != null && strH.length() != 0) { 63                 height = Integer.parseInt(strH); 64             } 65             if (strW != null && strW.length() != 0) { 66                 width = Integer.parseInt(strW); 67             } 68             if (strCodeNums != null && strCodeNums.length() != 0) { 69                 codeNum = Integer.parseInt(strCodeNums); 70             } 71         } catch (NumberFormatException e) { 72         } 73  74         x = width / (codeNum + 1); 75         fontHeight = height - 2; 76         codeY = height - 4; 77  78     } 79  80     protected void doGet(HttpServletRequest req, HttpServletResponse resp) 81             throws ServletException, java.io.IOException { 82         // 定义验证码图像的缓冲流 83         BufferedImage buffImg = new BufferedImage(width, height, 84                 BufferedImage.TYPE_INT_RGB); 85         // 产生图形上下文 86         Graphics2D g = buffImg.createGraphics(); 87  88         // 创建随机数产生函数 89         Random random = new Random(); 90  91         // 将验证码图像背景填充为白色 92         g.setColor(getRandColor(210, 260)); 93         g.fillRect(0, 0, width, height); 94  95         // 创建字体格式,字体的大小则根据验证码图片的高度来设定。 96         Font font = new Font("Fixedsys", Font.PLAIN, fontHeight); 97         // 设置字体。 98         g.setFont(font); 99 100         // 为验证码图片画边框,为一个像素。101         g.setColor(Color.BLACK);102         g.drawRect(0, 0, width - 1, height - 1);103 104         // 随机生产120跳图片干扰线条,使验证码图片中的字符不被轻易识别105         g.setColor(getRandColor(110, 240));106         for (int i = 0; i < 120; i++) {107             int x = random.nextInt(width);108             int y = random.nextInt(height);109             int xl = random.nextInt(12);110             int yl = random.nextInt(12);111             g.drawLine(x, y, x + xl, y + yl);112         }113 114         // randomCode保存随机产生的验证码115         StringBuffer randomCode = new StringBuffer();116 117         // 定义颜色三素118         int red = 0, green = 0, blue = 0;119 120         // 随机生产codeNum个数字验证码121         for (int i = 0; i < codeNum; i++) {122             // 得到随机产生的验证码123             String strRand = String.valueOf(codes[random.nextInt(35)]);124             // 使用随机函数产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。125             126 127             // 用随机产生的颜色将验证码绘制到图像中。128             g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));129 130             g.drawString(strRand, (i + 1) * x, codeY);131 132             // 将产生的四个随机数组合在一起。133             randomCode.append(strRand);134         }135         // 将生产的验证码保存到Session中136         HttpSession session = req.getSession();137         session.setAttribute("imgcheck", randomCode.toString());138 139         // 设置图像缓存为no-cache。140         resp.setHeader("Pragma", "no-cache");141         resp.setHeader("Cache-Control", "no-cache");142         resp.setDateHeader("Expires", 0);143 144         resp.setContentType("image/jpeg");145 146         // 将最终生产的验证码图片输出到Servlet的输出流中147         ServletOutputStream sos = resp.getOutputStream();148         ImageIO.write(buffImg, "jpeg", sos);149         sos.close();150         151     }152 153     protected void doPost(HttpServletRequest req, HttpServletResponse resp)154             throws ServletException, IOException {155         doGet(req, resp);156     }157 158 }

3.登陆时验证:

String img=request.getParameter("Imgcheck");                HttpSession session = request.getSession();String yzm = (String) session.getAttribute("imgcheck");

对比 img的内容是否与yzm的内容是否一致。

图片验证码