码迷,mamicode.com
首页 > 编程语言 > 详细

Java-生成指定长度验证码的一种简单思路

时间:2016-09-06 16:59:05      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:

 前言:以前做过的一个项目,刚开的时候始验证码是在前端生成前端验证的,后来觉得不靠谱,另外就是找回密码的功能也需要发送邮件和短信的验证码,所以,验证码就必须在后端生成并且保存到应用会话中才行了!所以,就有了下面的这段简单的代码,这段代码虽然简单,但也是生成验证码的一种思路,在此小记一笔以备后用。

1:如下是生成验证码、测试生成验证码的方法,比较简单,注释也比较清楚,不多说了

package start;

import java.util.Random;

public class HelloMain {
    /**
     * 主函数,作为调用和测试生成验证码方法的入口
     * @param args
     */
    public static void main(String[] args)
    {
            for(int i=0; i<10;i++)
            {
                System.out.println("【"+i+"】"+"      【the verification code is】       "+createVerificationCode(6));
            }
    }
    /**
     * 生成指定长度的验证码
     * @author Q
     * @param verificationCodeLength
     * @return String
     * @since 2016-09-6
     */
    public static final String createVerificationCode(int verificationCodeLength) 
    {
        //    所有候选组成验证码的字符,可以用中文
        String[] verificationCodeArrary={"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
               "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",
               "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 verificationCode = "";
        Random random = new Random();
        //此处是生成验证码的核心了,利用一定范围内的随机数做为验证码数组的下标,循环组成我们需要长度的验证码,做为页面输入验证、邮件、短信验证码验证都行
        for(int i=0;i<verificationCodeLength;i++){verificationCode += verificationCodeArrary[random.nextInt(verificationCodeArrary.length)];}
        return verificationCode;
    }
}

2:如下是运行主函数生十组六位长度验证码的运行结果演示图

技术分享

3:小结

此例的核心和JS-改变页面的颜色之变化核心-获取六位的随机数类似,都需要利用随机数函数来模拟生成六位随机数经过处理一下后,前者作为验证码后者作为颜色的十六进制六位表示值。

 

Java-生成指定长度验证码的一种简单思路

标签:

原文地址:http://www.cnblogs.com/godtrue/p/5845952.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!