springboot验证码功能实现

本文介绍了如何在Spring Boot项目中集成Kaptcha库,配置验证码的参数,并在控制器和前端页面实现动态刷新验证码的功能。重点展示了配置类和get请求的代码示例,以及前端模板的整合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.引入pom

<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

2.编写配置类(KaptchaConfig)

@Configuration
public class KaptchaConfig {
    @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","black");
        //字符范围
        properties.setProperty("kaptcha.textproducer.char.string","0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
        //字符数量
        properties.setProperty("kaptcha.textproducer.char.length","4");
        //字符干扰模式
        //properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");//去掉字符干扰

        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Config config = new Config(properties);
        kaptcha.setConfig(config);
        return kaptcha;
    }
}

3.编写get请求(controller层)

@GetMapping("/kaptcha")
public void getKaptcha(HttpServletResponse response, HttpSession session) {
    //生成验证码
    String text = kaptchaProducer.createText();
    BufferedImage image = kaptchaProducer.createImage(text);

    //将验证码存入session
    session.setAttribute("kaptcha", image);

    //将图片传给浏览器
    response.setContentType("image/png");
    try {
        OutputStream os = response.getOutputStream();
        ImageIO.write(image, "PNG", os);
    } catch (IOException e) {
        logger.error("图片输出错误" + e.getMessage());
    }
}

在这里插入图片描述

4.将请求嵌入前端模板

<div class="form-group row mt-4">
	<label for="verifycode" class="col-sm-2 col-form-label text-right">验证码:</label>
	<div class="col-sm-6">
		<input type="text" class="form-control is-invalid" id="verifycode" placeholder="请输入验证码!">
		<div class="invalid-feedback">
			验证码不正确!
		</div>
	</div>
	<div class="col-sm-4">
		<img th:src="@{/kaptcha}" id="kaptcha" style="width:100px;height:40px;" class="mr-2"/>
		<a href="javascript:refresh_kaptcha();"  class="font-size-12 align-bottom">刷新验证码</a>
	</div>
</div>

5.编写js实现点击动态刷新

<script>
       function refresh_kaptcha(){
           const path = CONTEXT_PATH + "/kaptcha?P=" + Math.random();
           $("#kaptcha").attr("src",path);
    }
</script>

将请求路径拼接后随机填入数字,get请求不变,防止浏览器默认请求未变化造成刷新失败
点击看gitee源码!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值