zoukankan      html  css  js  c++  java
  • 基于struts2+hibernate+spring(ssh2)的登录验证码的实现

    验证码是很多系统都需要的,今天搞了一下午终于把验证码的功能实现了,可以显示三种不同类型的验证码而不是单独一种,显示效果如下图所示:

    * 第一种:简单验证码,4位随机数字 :

    * 第二种:英文字符加数字的验证码 :

    * 第三种:像铁路订票系统一样的验证码,肆+?=21


    下面是实现的验证码类

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



    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.     ActionContext.getContext().getSession().put("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="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" onclick="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.     }  
     
    分享到:

    package com.base.util;

    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.util.Random;
    import javax.imageio.ImageIO;
    import javax.imageio.stream.ImageOutputStream;

    /**
     * 验证码类,主要生成几种不同类型的验证码
     * 第一种:简单验证码,4位随机数字
     * 第二种:英文字符加数字的验证码
     * 第三种:像铁路订票系统一样的验证码,肆+?=21
     *
     * @author 李朋飞
     *
     */
    public class VerificationCodeUtil {
        private ByteArrayInputStream image;// 图像
        private String str;// 验证码
        private static final int WIDTH = 80;
        private static final int HEIGHT = 20;

        public static void main(String[] arg) {
            VerificationCodeUtil vcu = VerificationCodeUtil.Instance();
            System.err.println(vcu.getVerificationCodeValue());
        }

        /**
         * 功能:获取一个验证码类的实例
         *
         * @return
         */
        public static VerificationCodeUtil Instance() {
            return new VerificationCodeUtil();
        }

        private VerificationCodeUtil() {
            BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
                    BufferedImage.TYPE_INT_RGB);
            int randomNum = new Random().nextInt(3);
            if (randomNum == 0) {
                initNumVerificationCode(image);
            } else if (randomNum == 1) {
                initLetterAndNumVerificationCode(image);
            } else {
                initChinesePlusNumVerificationCode(image);
            }
        }

        /**
         * 功能:设置第一种验证码的属性
         */
        public void initNumVerificationCode(BufferedImage image) {

            Random random = new Random(); // 生成随机类
            Graphics g = initImage(image, random);
            String sRand = "";
            for (int i = 0; i < 4; i++) {
                String rand = String.valueOf(random.nextInt(10));
                sRand += rand;
                // 将认证码显示到图象中
                g.setColor(new Color(20 + random.nextInt(110), 20 + random
                        .nextInt(110), 20 + random.nextInt(110)));
                // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
                g.drawString(rand, 13 * i + 6, 16);
            }
            this.setStr(sRand);/* 赋值验证码 */
            // 图象生效
            g.dispose();
            this.setImage(drawImage(image));
        }

        /**
         * 功能:设置第二种验证码属性
         */
        public void initLetterAndNumVerificationCode(BufferedImage image) {

            Random random = new Random(); // 生成随机类
            Graphics g = initImage(image, random);
            String[] letter = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
                    "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                    "W", "X", "Y", "Z" };
            String sRand = "";
            for (int i = 0; i < 4; i++) {
                String tempRand = "";
                if (random.nextBoolean()) {
                    tempRand = String.valueOf(random.nextInt(10));
                } else {
                    tempRand = letter[random.nextInt(25)];
                    if (random.nextBoolean()) {// 随机将该字母变成小写
                        tempRand = tempRand.toLowerCase();
                    }
                }
                sRand += tempRand;
                g.setColor(new Color(20 + random.nextInt(10), 20 + random
                        .nextInt(110), 20 + random.nextInt(110)));
                g.drawString(tempRand, 13 * i + 6, 16);
            }
            this.setStr(sRand);/* 赋值验证码 */
            g.dispose(); // 图象生效
            this.setImage(drawImage(image));
        }

        /**
         * 功能:设置第三种验证码属性 即:肆+?=24
         */
        public void initChinesePlusNumVerificationCode(BufferedImage image) {
            String[] cn = { "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "拾" };
            Random random = new Random(); // 生成随机类
            Graphics g = initImage(image, random);
            int x = random.nextInt(10) + 1;
            int y = random.nextInt(30);
            this.setStr(String.valueOf(y));
            g.setFont(new Font("楷体", Font.PLAIN, 14));// 设定字体
            g.setColor(new Color(20 + random.nextInt(10), 20 + random.nextInt(110),
                    20 + random.nextInt(110)));
            g.drawString(cn[x - 1], 1 * 1 + 6, 16);
            g.drawString("+", 22, 16);
            g.drawString("?", 35, 16);
            g.drawString("=", 48, 16);
            g.drawString(String.valueOf(x + y), 61, 16);
            g.dispose(); // 图象生效
            this.setImage(drawImage(image));

        }

        public Graphics initImage(BufferedImage image, Random random) {
            Graphics g = image.getGraphics(); // 获取图形上下文
            g.setColor(getRandColor(200, 250));// 设定背景色
            g.fillRect(0, 0, WIDTH, HEIGHT);
            g.setFont(new Font("Times New Roman", Font.PLAIN, 14));// 设定字体
            g.setColor(getRandColor(160, 200)); // 随机产生165条干扰线,使图象中的认证码不易被其它程序探测到
            for (int i = 0; i < 165; 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);
            }
            return g;
        }

        public ByteArrayInputStream drawImage(BufferedImage image) {
            ByteArrayInputStream input = null;
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try {
                ImageOutputStream imageOut = ImageIO
                        .createImageOutputStream(output);
                ImageIO.write(image, "JPEG", imageOut);
                imageOut.close();
                input = new ByteArrayInputStream(output.toByteArray());
            } catch (Exception e) {
                System.out.println("验证码图片产生出现错误:" + e.toString());
            }
            return input;
        }

        /*
         * 功能:给定范围获得随机颜色
         */
        private 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);
        }

        /**
         * 功能:获取验证码的字符串值
         *
         * @return
         */
        public String getVerificationCodeValue() {
            return this.getStr();
        }

        /**
         * 功能:取得验证码图片
         *
         * @return
         */
        public ByteArrayInputStream getImage() {
            return this.image;
        }

        public String getStr() {
            return str;
        }

        public void setStr(String str) {
            this.str = str;
        }

        public void setImage(ByteArrayInputStream image) {
            this.image = image;
        }
    }

  • 相关阅读:
    解决打开GitHub慢的问题
    RestFramework规范简介
    在Linux中持久化运行项目
    Linux安装Mysql
    Java基础内容汇总[持续更新]
    Elasticsearch内容汇总[持续更新]
    深入源码理解SpringBean生命周期
    利用JVM钩子函数优雅关闭线程池
    聊聊消息队列高性能的秘密——零拷贝技术
    Elasticsearch性能优化汇总——写入&搜索
  • 原文地址:https://www.cnblogs.com/lanxuezaipiao/p/2583636.html
Copyright © 2011-2022 走看看