全文地址请点击:https://blog.csdn.net/u012191462/article/details/45370597
在做web开发的时候,常常需要使用到验证码。验证码的作用其实非常重要,通过它可以有效的防止有人通过使用暴力的手段破解掉用户的账号密码信息,验证码是一串随机生成的数字组合,而最重要的就是它具有扰乱人眼的背景图片。在互联网盛行的今天,信息安全更显得重要,所以验证码对于web开发必不可少。在后面的文章里,我还会谈谈在移动客户端上如何实现验证码这一重要的功能。
先看一看程序运行的效果:
很简单,只需要输入一个用户名和正确的验证码即可进入首页,否则提示出相应的错误信息。下面我们来看看程序是如何实现的:为了方便,代码写在了jsp页面中
1 <%@ page import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" pageEncoding="gbk"%> 2 <%@ page import="java.io.OutputStream"%> 3 4 <%-- 采用JPG格式的图片验证码 --%> 5 6 <%!Color getRandColor(int fc, int bc) //随机生成图片中rgb的值 7 { 8 Random random = new Random(); 9 if (fc > 255) 10 fc = 255; 11 12 if (bc > 255) 13 bc = 255; 14 15 int r = fc + random.nextInt(bc - fc); 16 17 int g = fc + random.nextInt(bc - fc); 18 19 int b = fc + random.nextInt(bc - fc); 20 21 return new Color(r, g, b); 22 } 23 %> 24 25 <% 26 try 27 { 28 response.setHeader("Pragma", "No-cache"); 29 30 response.setHeader("Cache-Control", "no-cache"); 31 32 response.setDateHeader("Expires", 0); 33 34 int width = 60, height = 20; 35 36 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 37 38 OutputStream os = response.getOutputStream(); 39 40 Graphics g = image.getGraphics(); 41 42 Random random = new Random(); 43 44 // 设置画笔的颜色 45 g.setColor(getRandColor(200, 250)); 46 47 // 画图,生成干扰图片 48 g.fillRect(0, 0, width, height); 49 50 //字体等样式 51 g.setFont(new Font("Times New Roman", Font.PLAIN, 18)); 52 53 g.setColor(getRandColor(160, 200)); 54 55 //生成图像内部的干扰线条 56 for (int i = 0; i < 155; i++) 57 { 58 int x = random.nextInt(width); 59 int y = random.nextInt(height); 60 int xl = random.nextInt(12); 61 int yl = random.nextInt(12); 62 63 //绘制干扰线条 64 g.drawLine(x, y, x + xl, y + yl); 65 } 66 67 String sRand = ""; 68 69 //生成4为随机的、有彩色值得验证码 70 for (int i = 0; i < 4; i++) 71 { 72 //生成一位验证码的值 73 String rand = String.valueOf(random.nextInt(10)); 74 75 sRand += rand; 76 77 g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110))); 78 79 //对生成的验证码值进行颜色设置,已进行干扰 80 g.drawString(rand, 13 * i + 6, 16); 81 } 82 83 session.setAttribute("yanzhengma_InSession", sRand); 84 85 g.dispose(); 86 87 //生成JPEG格式的图片验证码 88 ImageIO.write(image, "JPEG", os); 89 90 os.flush(); 91 os.close(); 92 93 os = null; 94 95 // 用来将缓冲区的数据立即输出到浏览器当中 96 response.flushBuffer(); 97 98 /* 两句关键代码 */ 99 out.clear(); 100 101 out = pageContext.pushBody(); 102 } 103 catch (IllegalStateException e) 104 { 105 System.out.println(e.getMessage()); 106 e.printStackTrace(); 107 } 108 %>
具体的解释代码中已经注释的很清楚了,其实就是通过一张图片,在上面生成了一系列的干扰线条,从而使得破解程序无法进行识别,这里我们采用的是JPG格式的图片验证码,其他的方式还有好几种,这里不再叙述,当然现在验证码的花样也越来越多,原理都是不变的。
特别要提出的是out对象,out.clear()的作用是清空缓存,这里必须添加这两句话,out对象的另一个方法clearBuffer()作用是清空缓存的同时将其内容输出,具体的大家自己可以进行测试,由于上传了好多次,都没看到,所以这里先不提供源码下载,在后面将进行补充。