验证码使用流程

创建配置类

@Configuration
public class CaptchaConfig {

    /**
     * 配置Producer接口的实现类DefaultKaptcha的bean对象,该对象用于生成验证码图片;
     * 并给其指定生成的验证码图片的设置项;bean对象的id引用名为captchaProducer;
     */
    @Bean(name = "captchaProducer")
    public DefaultKaptcha getKaptchaBean() {

        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();

        Properties properties = new Properties();
        //是否有边框 默认为true 我们可以自己设置yes,no
        properties.setProperty("kaptcha.border", "yes");
        //边框颜色 默认为Color.BLACK
        properties.setProperty("kaptcha.border.color", "105,179,90");
        //验证码文本字符颜色 默认为Color.BLACK
        properties.setProperty("kaptcha.textproducer.font.color", "blue");
        //验证码图片宽度 默认为200
        properties.setProperty("kaptcha.image.width", "120");
        //验证码图片高度 默认为50
        properties.setProperty("kaptcha.image.height", "40");
        //验证码文本字符大小 默认为40
        properties.setProperty("kaptcha.textproducer.font.size", "32");
        //KAPTCHA_SESSION_KEY
        properties.setProperty("kaptcha.session.key", "kaptchaCode");
        //验证码文本字符间距 默认为2
        properties.setProperty("kaptcha.textproducer.char.space", "4");
        //验证码文本字符长度 默认为5
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        //验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
        properties.setProperty("kaptcha.textproducer.font.names", "Arial,Courier");
        //验证码噪点颜色 默认为Color.BLACK
        properties.setProperty("kaptcha.noise.color", "gray");

        Config config = new Config(properties);

        defaultKaptcha.setConfig(config);

        return defaultKaptcha;
    }
}

2. 生成验证码返回给前端

@Resource(name ="captchaProducer")
private Producer catchproducer;
@GetMapping("/captchaImage")
public void getKaptchaImage(HttpServletResponse response){
    //将图片传给response
    ServletOutputStream out = null;
    try {
        //生成验证码文本
        String code = catchproducer.createText();
        //生成图片
        BufferedImage image = catchproducer.createImage(code);
        //将图片放到redis,验证时获取当前输入的验证码与redis保存的键是否一致
        redisTemplate.opsForValue().set(code,code);
        out = response.getOutputStream();
        ImageIO.write(image,"jpg",out);
        out.flush();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }finally {

            try {
                if (out!=null) {
                    out.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
    }
  • 16
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值