几种验证码的生成

  1. import java.awt.Color;  
  2. import java.awt.Font;  
  3. import java.awt.Graphics;  
  4. import java.awt.image.BufferedImage;  
  5. import java.io.ByteArrayInputStream;  
  6. import java.io.ByteArrayOutputStream;  
  7. import java.util.Random;  
  8. import javax.imageio.ImageIO;  
  9. import javax.imageio.stream.ImageOutputStream;  
  10.   
  11. /** 
  12.  * 验证码类,主要生成几种不同类型的验证码  
  13.  * 第一种:简单验证码,4位随机数字  
  14.  * 第二种:英文字符加数字的验证码  
  15.  * 第三种:像铁路订票系统一样的验证码,肆+?=21 
  16.  *  
  17.  * @author 李朋飞 
  18.  *  
  19.  */  
  20. public class VerificationCodeUtil {  
  21.     private ByteArrayInputStream image;// 图像  
  22.     private String str;// 验证码  
  23.     private static final int WIDTH = 80;  
  24.     private static final int HEIGHT = 20;  
  25.   
  26.     public static void main(String[] arg) {  
  27.         VerificationCodeUtil vcu = VerificationCodeUtil.Instance();  
  28.         System.err.println(vcu.getVerificationCodeValue());  
  29.     }  
  30.   
  31.     /** 
  32.      * 功能:获取一个验证码类的实例 
  33.      *  
  34.      * @return 
  35.      */  
  36.     public static VerificationCodeUtil Instance() {  
  37.         return new VerificationCodeUtil();  
  38.     }  
  39.   
  40.     private VerificationCodeUtil() {  
  41.         BufferedImage image = new BufferedImage(WIDTH, HEIGHT,  
  42.                 BufferedImage.TYPE_INT_RGB);  
  43.         int randomNum = new Random().nextInt(3);  
  44.         if (randomNum == 0) {  
  45.             initNumVerificationCode(image);  
  46.         } else if (randomNum == 1) {  
  47.             initLetterAndNumVerificationCode(image);  
  48.         } else {  
  49.             initChinesePlusNumVerificationCode(image);  
  50.         }  
  51.     }  
  52.   
  53.     /** 
  54.      * 功能:设置第一种验证码的属性 
  55.      */  
  56.     public void initNumVerificationCode(BufferedImage image) {  
  57.   
  58.         Random random = new Random(); // 生成随机类  
  59.         Graphics g = initImage(image, random);  
  60.         String sRand = "";  
  61.         for (int i = 0; i < 4; i++) {  
  62.             String rand = String.valueOf(random.nextInt(10));  
  63.             sRand += rand;  
  64.             // 将认证码显示到图象中  
  65.             g.setColor(new Color(20 + random.nextInt(110), 20 + random  
  66.                     .nextInt(110), 20 + random.nextInt(110)));  
  67.             // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成  
  68.             g.drawString(rand, 13 * i + 616);  
  69.         }  
  70.         this.setStr(sRand);/* 赋值验证码 */  
  71.         // 图象生效  
  72.         g.dispose();  
  73.         this.setImage(drawImage(image));  
  74.     }  
  75.   
  76.     /** 
  77.      * 功能:设置第二种验证码属性 
  78.      */  
  79.     public void initLetterAndNumVerificationCode(BufferedImage image) {  
  80.   
  81.         Random random = new Random(); // 生成随机类  
  82.         Graphics g = initImage(image, random);  
  83.         String[] letter = { "A""B""C""D""E""F""G""H""I""J",  
  84.                 "K""L""M""N""O""P""Q""R""S""T""U""V",  
  85.                 "W""X""Y""Z" };  
  86.         String sRand = "";  
  87.         for (int i = 0; i < 4; i++) {  
  88.             String tempRand = "";  
  89.             if (random.nextBoolean()) {  
  90.                 tempRand = String.valueOf(random.nextInt(10));  
  91.             } else {  
  92.                 tempRand = letter[random.nextInt(25)];  
  93.                 if (random.nextBoolean()) {// 随机将该字母变成小写  
  94.                     tempRand = tempRand.toLowerCase();  
  95.                 }  
  96.             }  
  97.             sRand += tempRand;  
  98.             g.setColor(new Color(20 + random.nextInt(10), 20 + random  
  99.                     .nextInt(110), 20 + random.nextInt(110)));  
  100.             g.drawString(tempRand, 13 * i + 616);  
  101.         }  
  102.         this.setStr(sRand);/* 赋值验证码 */  
  103.         g.dispose(); // 图象生效  
  104.         this.setImage(drawImage(image));  
  105.     }  
  106.   
  107.     /** 
  108.      * 功能:设置第三种验证码属性 即:肆+?=24 
  109.      */  
  110.     public void initChinesePlusNumVerificationCode(BufferedImage image) {  
  111.         String[] cn = { "壹""贰""叁""肆""伍""陆""柒""捌""玖""拾" };  
  112.         Random random = new Random(); // 生成随机类  
  113.         Graphics g = initImage(image, random);  
  114.         int x = random.nextInt(10) + 1;  
  115.         int y = random.nextInt(30);  
  116.         this.setStr(String.valueOf(y));  
  117.         g.setFont(new Font("楷体", Font.PLAIN, 14));// 设定字体  
  118.         g.setColor(new Color(20 + random.nextInt(10), 20 + random.nextInt(110),  
  119.                 20 + random.nextInt(110)));  
  120.         g.drawString(cn[x - 1], 1 * 1 + 616);  
  121.         g.drawString("+"2216);  
  122.         g.drawString("?"3516);  
  123.         g.drawString("="4816);  
  124.         g.drawString(String.valueOf(x + y), 6116);  
  125.         g.dispose(); // 图象生效  
  126.         this.setImage(drawImage(image));  
  127.   
  128.     }  
  129.   
  130.     public Graphics initImage(BufferedImage image, Random random) {  
  131.         Graphics g = image.getGraphics(); // 获取图形上下文  
  132.         g.setColor(getRandColor(200250));// 设定背景色  
  133.         g.fillRect(00, WIDTH, HEIGHT);  
  134.         g.setFont(new Font("Times New Roman", Font.PLAIN, 14));// 设定字体  
  135.         g.setColor(getRandColor(160200)); // 随机产生165条干扰线,使图象中的认证码不易被其它程序探测到  
  136.         for (int i = 0; i < 165; i++) {  
  137.             int x = random.nextInt(WIDTH);  
  138.             int y = random.nextInt(HEIGHT);  
  139.             int xl = random.nextInt(12);  
  140.             int yl = random.nextInt(12);  
  141.             g.drawLine(x, y, x + xl, y + yl);  
  142.         }  
  143.         return g;  
  144.     }  
  145.   
  146.     public ByteArrayInputStream drawImage(BufferedImage image) {  
  147.         ByteArrayInputStream input = null;  
  148.         ByteArrayOutputStream output = new ByteArrayOutputStream();  
  149.         try {  
  150.             ImageOutputStream imageOut = ImageIO  
  151.                     .createImageOutputStream(output);  
  152.             ImageIO.write(image, "JPEG", imageOut);  
  153.             imageOut.close();  
  154.             input = new ByteArrayInputStream(output.toByteArray());  
  155.         } catch (Exception e) {  
  156.             System.out.println("验证码图片产生出现错误:" + e.toString());  
  157.         }  
  158.         return input;  
  159.     }  
  160.   
  161.     /* 
  162.      * 功能:给定范围获得随机颜色 
  163.      */  
  164.     private Color getRandColor(int fc, int bc) {  
  165.         Random random = new Random();  
  166.         if (fc > 255)  
  167.             fc = 255;  
  168.         if (bc > 255)  
  169.             bc = 255;  
  170.         int r = fc + random.nextInt(bc - fc);  
  171.         int g = fc + random.nextInt(bc - fc);  
  172.         int b = fc + random.nextInt(bc - fc);  
  173.         return new Color(r, g, b);  
  174.     }  
  175.   
  176.     /** 
  177.      * 功能:获取验证码的字符串值 
  178.      *  
  179.      * @return 
  180.      */  
  181.     public String getVerificationCodeValue() {  
  182.         return this.getStr();  
  183.     }  
  184.   
  185.     /** 
  186.      * 功能:取得验证码图片 
  187.      *  
  188.      * @return 
  189.      */  
  190.     public ByteArrayInputStream getImage() {  
  191.         return this.image;  
  192.     }  
  193.   
  194.     public String getStr() {  
  195.         return str;  
  196.     }  
  197.   
  198.     public void setStr(String str) {  
  199.         this.str = str;  
  200.     }  
  201.   
  202.     public void setImage(ByteArrayInputStream image) {  
  203.         this.image = image;  
  204.     }  
  205. }  

struts2中获得验证码: 
Java代码   收藏代码
  1. /** 
  2.  * 功能:打开login.jsp的时候获得随机的验证码图片 
  3.  *  
  4.  * @return 
  5.  */  
  6. public String getRandomPictrue() {  
  7.     VerificationCodeUtil vcu = VerificationCodeUtil.Instance();  
  8.     this.setInputStream(vcu.getImage());  
  9.     this.setSessionAttribute("random", vcu.getVerificationCodeValue());// 取得随机字符串放入HttpSession  
  10.     return SUCCESS;  
  11.   
  12. }  


另外前台jsp页面 

Java代码   收藏代码
  1.   <script type="text/javascript">     
  2.     function changeValidateCode(obj) {     
  3.            //获取当前的时间作为参数,无具体意义     
  4.         var timenow = new Date().getTime();     
  5.            //每次请求需要一个不同的参数,否则可能会返回同样的验证码     
  6.         //这和浏览器的缓存机制有关系,也可以把页面设置为不缓存,这样就不用这个参数了。     
  7.         obj.src="getRandomPictrue?d="+timenow;     
  8.     }     
  9. </script>  
  10. <tr>  
  11.                 <td height="24" valign="bottom"><div align="right"><span class="STYLE3">验证码</span></div></td>  
  12.                 <td width="10" valign="bottom">&nbsp;</td>  
  13.                 <td width="52" height="24" valign="bottom"><input type="text"  maxlength=4 name="yzm" id="textfield3" style="width:50px; height:17px; background-color:#87adbf; border:solid 1px #153966; font-size:12px; color:#283439; "></td>  
  14.                 <td width="92" valign="bottom"><div align="center"><img src="getRandomPictrue.action" width="80" height="20" οnclick="changeValidateCode(this)"></div></td>  
  15.               </tr>   


另外,在登录的时候,后台验证验证码是否输入正确 
Java代码   收藏代码
  1. public String userLogin() {  
  2.         String yanzhengma = this.getYzm().toLowerCase();//将验证码字符串全部转换成小写  
  3.         String random = getSessionAttribute("random").toString().toLowerCase();        
  4.         if(!yanzhengma.equals(random)){  
  5.             this.setRequestAttribute("errorMessage""验证码错误,请核实后重新输入");  
  6.             return INPUT;  
  7.         }  
  8.         else{  
  9.             UserModel user = getUserService().loginJudge(getUserName(),  
  10.                     getUserPass());  
  11.             if (user != null) {  
  12.                 getSession().setAttribute("user", user);  
  13.                 getSession().setAttribute("userId", user.getUserId());  
  14.                 List<PermissionModel> treeList = userService.getTree(user  
  15.                         .getUserId());  
  16.                 getRequest().setAttribute("treeList", treeList);  
  17.                 this.setRequestAttribute("username", user.getUserName());  
  18.                 user.setLastLoginTime(DateUtil.getCurrentTimestamp());  
  19.                 if (userService.addUser(user)) {  
  20.                     logger.info(getUserName() + "登录成功");  
  21.                     return SUCCESS;  
  22.                 } else {  
  23.                     logger.info(getUserName() + "登录失败,失败原因,更新lastLoginTime失败");  
  24.                     this.setRequestAttribute("errorMessage""服务器hold不住啦,请稍后重新登录");  
  25.                     return INPUT;  
  26.                 }  
  27.             } else {  
  28.                 logger.info(getUserName() + "登录失败,用户名或者密码不正确");  
  29.                 this.setRequestAttribute("errorMessage""登录失败,用户名或者密码不正确");  
  30.                 return INPUT;  
  31.             }  
  32.         }  
  33.           
  34.     }  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值