您的位置:首页 > 编程语言 > Java开发

带加减法的图片验证码(java编程实现)

2013-11-12 16:21 447 查看
最近用java做了一个加法验证码,是在kaptcha的基础上改写的,而kaptcha是一个扩展自 simplecaptcha的验证码库。
// create the text for the image
List<String> capText = createText();
// store the text in the session
String sessionid = UserCookieUtil.getSessionId(request);
cacheManager.setCode(VerifyTypeEnum.IMG_CODE, sessionid, capText.get(1), timeout);
// create the image with the text
BufferedImage bi = captchaProducer.createImage(capText.get(0));
ServletOutputStream out = response.getOutputStream();
// write the data out
ImageIO.write(bi, "jpg", out);
try {
    out.flush();
} finally {
    out.close();

 

 

// create the text for the image
private List<String> createText() {
        int intFirst, intSec, intTemp, validCodeResult;
        String validCode = null;
        Random rand = new Random();
        intFirst = (int) (Math.random() * 10);
        intSec = (int) (Math.random() * 10);
        switch (rand.nextInt(3)) {
        case 0:
            if (intFirst < intSec) {
                intTemp = intFirst;
                intFirst = intSec;
                intSec = intTemp;
            }
            validCode = intFirst + "-" + intSec + "=?";
            validCodeResult = intFirst - intSec;
            break;
        case 1:
            validCode = intFirst + "+" + intSec + "=?";
            validCodeResult = intFirst + intSec;
            break;
        default:
            validCode = intFirst + "*" + intSec + "=?";
            validCodeResult = intFirst * intSec;
            break;
        }
        List<String> list = new ArrayList<String>();
        list.add(validCode);
        list.add(String.valueOf(validCodeResult));
        return list;
    }
下面再补充几种验证码

(1)// 由0-9组成的全数字验证码

  public static void numCode() {

        System.out.print("获取4位数字验证码:");

        for (int i = 0; i < 4; i++) {

            int n = rd.nextInt(10);

            System.out.print(n + " ");

        }

        System.out.println();

  }

(2)// 英文字母和标点符号组成的字符验证码

  public static void charCode() {

        System.out.print("获取4位字符验证码:");

        for (int i = 0; i < 4; i++) {

            int n = 65 + rd.nextInt(58);

            System.out.print((char) n);

        }

        System.out.println();

    }

(3)// 全部由中文组成的验证码

   public static void chineseCode() {

        System.out.print("获取4位汉字验证码:");

        for (int i = 0; i < 4; i++) {

            int n = 20000 + rd.nextInt(10000);

            System.out.print((char) n);

        }

        System.out.println();

    }

(4)// 字符+数字的混合验证码

  public static void mixCode() {

        System.out.print("\n获取的5位混合验证码:");

        for (int i = 0; i < 4; i++) {

            int n = rd.nextInt(123);

            if (n < 65) {

                System.out.print(n % 10);

            } else {

                System.out.print((char) n);

            }

        }

   }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: