栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring boot 图文验证码(Kaptcha)使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring boot 图文验证码(Kaptcha)使用

用法:

可以直接去官网http://code.google.com/p/kaptcha/下载jar,或者在pom.xml中导入


    com.google.code.kaptcha
    kaptcha
    2.3

或者(两者选其一即可)


    com.github.penggle
    kaptcha
    2.3.2

Kaptcha 详细配置表

常量描述默认值
kaptcha.border图片是否有边框默认true
kaptcha.border.color边框颜色
kaptcha.image.width验证码图片宽默认200
kaptcha.image.height验证码图片高默认50
kaptcha.textproducer.font.size验证码文本字符大小默认为40
kaptcha.session.key

session key

KAPTCHA_SESSION_KEY

kaptcha.textproducer.char.length验证码文本字符长度默认为5
kaptcha.textproducer.font.names验证码文本字体样式默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
kaptcha.obscurificator.impl图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
kaptcha.textproducer.impl验证码文本生成规则
kaptcha.textproducer.char.space验证码文本字符间距默认为2
kaptcha.noise.color验证码干扰颜色默认为Color.BLACK
kaptcha.noise.impl干扰实现类com.google.code.kaptcha.impl.NoNoise
kaptcha.background.impl背景实现类com.google.code.kaptcha.impl.DefaultBackground
kaptcha.producer.impl

图片实现类

com.google.code.kaptcha.impl.DefaultKaptcha

kaptcha.textproducer.impl

文本实现类

com.google.code.kaptcha.text.impl.DefaultTextCreator

kaptcha.textproducer.char.string文本集合
kaptcha.background.clear.from 背景颜色渐变,开始颜色
kaptcha.background.clear.to背景颜色渐变, 结束颜色
kaptcha.session.date

session date

KAPTCHA_SESSION_DATE

业务代码

@Service
public class CaptchaService extends baseService {

    // 对应CaptchaConfig 定义的bean name
    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    RedisOps redisOps;


    
    public DataRespBean> getPictureCaptcha(HttpServletResponse response) throws IOException {
        String uuid = UUID.randomUUID().toString();
        String capStr = null, code = null;
        BufferedImage image = null;
        // 生成验证码
        String capText = captchaProducerMath.createText();
        //截取结果
        capStr = capText.substring(0, capText.lastIndexOf("@"));
        code = capText.substring(capText.lastIndexOf("@") + 1);
        image = captchaProducerMath.createImage(capStr);
        //结果存入redis,key为uuid 超时时间5分钟
        redisOps.set(RedisUtil.pictureCaptchaKey(uuid), code, 5 * 60); // 5分钟
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        Map map = new HashMap<>();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return new DataRespBean(ResultCodeMsg.SERVER_ERROR.getErrMsg(), e.getMessage());
        }finally {
            map.put("uuid", uuid);
            map.put("img", base64Encoder.encode(os.toByteArray()));
            os.close();
        }
        return new DataRespBean<>(map);
    }
}

验证码生成规则(根据实际需求修改)

public class KaptchaTextCreator extends DefaultTextCreator {

    private static final String[] NUMBER= "0,1,2,3,4,5,6,7,8,9,10".split(",");

    @Override
    public String getText() {
        Integer result = 0;//结果
        Random random = new Random();
        int x = random.nextInt(10);
        int y = random.nextInt(10);
        StringBuilder suChinese = new StringBuilder();
        int randomop = (int) random.nextInt(4)
        //判断结果生成加减乘除
        if (randomop == 0) {
            result = x * y;
            suChinese.append(NUMBER[x]);
            suChinese.append("*");
            suChinese.append(NUMBER[y]);
        } else if (randomop == 1) {
            if (!(x == 0) && y % x == 0) {
                result = y / x;
                suChinese.append(NUMBER[y]);
                suChinese.append("/");
                suChinese.append(NUMBER[x]);
            } else {
                result = x + y;
                suChinese.append(NUMBER[x]);
                suChinese.append("+");
                suChinese.append(NUMBER[y]);
            }
        } else if (randomop == 2) {
            if (x >= y) {
                result = x - y;
                suChinese.append(NUMBER[x]);
                suChinese.append("-");
                suChinese.append(NUMBER[y]);
            } else {
                result = y - x;
                suChinese.append(NUMBER[y]);
                suChinese.append("-");
                suChinese.append(NUMBER[x]);
            }
        } else {
            result = x + y;
            suChinese.append(NUMBER[x]);
            suChinese.append("+");
            suChinese.append(NUMBER[y]);
        }
        //拼接结果返回
        suChinese.append("=?@" + result);
        return suChinese.toString();
    }

生成图片验证码配置

@Configuration
public class CaptchaConfig {
    @Bean(name = "captchaProducerMath")
    public DefaultKaptcha getKaptchaBeanMath() {
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        // 图片边框
        properties.setProperty(KAPTCHA_BORDER, "yes");
        // 边框颜色
        properties.setProperty(KAPTCHA_BORDER_COLOR, "105,179,90");
        // 文本颜色
        properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue");
        // 图片宽度 
        properties.setProperty(KAPTCHA_IMAGE_WIDTH, "130");
        // 图片高度 
        properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "32");
        // 文本字符大小
        properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "28");
        // KAPTCHA_SESSION_KEY
        properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "KAPTCHA_SESSION_KEY");
        // 验证码文本生成器
        properties.setProperty(KAPTCHA_TEXTPRODUCER_IMPL, "对应自己的KaptchaTextCreator 文件路径");
        // 文本字符间距 
        properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, "3");
        // 文本字符长度
        properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "6");
        // 文本字体样式
        properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
        // 干扰颜色
        properties.setProperty(KAPTCHA_NOISE_COLOR, "white");
        // 干扰实现类
        properties.setProperty(KAPTCHA_NOISE_IMPL, "com.google.code.kaptcha.impl.NoNoise");
        // 图片样式
        properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

返回结果(jpg base64编码)

效果展示

  

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/317971.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号