springboot 使用验证码

首先导入依赖:

在这里插入图片描述

<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

完成配置文件:

@Configuration
public class KapthchaConfig {
    @Bean
    public Producer kaptchaProducer(){
        //用于设置验证码具体细节
        Properties properties = new Properties();
        //设置验证码图片宽度
        properties.setProperty("kaptcha.image.width", "100");
        //设置验证码图片高度
        properties.setProperty("kaptcha.image.height", "40");
        //设置验证码文字大小
        properties.setProperty("kaptcha.textproducer.font.size", "32");
        //设置验证码图片颜色
        properties.setProperty("kaptcha.textproducer.font.color", "0,0,0");
        //设置验证码文字内容
        properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYAZ");
        //设置生成随机字符数量
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        //图片干扰设置
        properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");

        //Kaptcha实现类
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        //将properties配置封装到Config对象中
        Config config = new Config(properties);
        //将config传入实现类
        kaptcha.setConfig(config);
        return kaptcha;
    }
}

复制过去 遇到类名冲突的 有Katpth的就选它 没有默认第一个。
在这里插入图片描述

完成controller 的配置:

@Controller
public class KapthchaController {
    //注入生成验证码所需要的Producer对象
    @Autowired
    private Producer kaptcha;

    /**
     * 获取验证码
     */
    @RequestMapping("/kaptcha")
    public void getKpthcha(HttpServletResponse response, HttpSession session){
        //生成验证码内容
        String text = kaptcha.createText();
        //生成验证码图片
        BufferedImage image = kaptcha.createImage(text);
        //将文字保存进session中
        session.setAttribute("code",text);
        //将图片写回流中,输出给浏览器
        response.setContentType("image/png");
        try {
            ServletOutputStream os = response.getOutputStream();
            ImageIO.write(image,"png",os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

前端如何实现:

js:
在这里插入图片描述
html:
在这里插入图片描述
可以实现点一下刷新验证码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值