验证码实现

本文展示了如何在Spring Boot项目中配置Kaptcha依赖,用于生成验证码。配置类定义了验证码的尺寸、字符集和长度。在Controller层,提供了两个接口,分别返回验证码的Base64字符串和图片格式。验证码的文本会存储在HttpSession中,可用于后续的验证过程。
摘要由CSDN通过智能技术生成

验证码依赖

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

配置类

@Configuration
public class KaptchaConfig {

    @Bean
    public Producer kaptcha(){
        Properties properties = new Properties();
        properties.setProperty("kaptcha.image.width","150");
        properties.setProperty("kaptcha.image.height","50");
        properties.setProperty("kaptcha.textproducer.char.string","0123456789");
        properties.setProperty("kaptcha.textproducer.char.length","4");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

controller层

base64格式

@RestController
public class VerifyController {
    @Autowired
    Producer producer;

    @GetMapping("/code")
    public String getVerifyCode(HttpSession session) throws IOException {
        //生成验证码
        String text = producer.createText();
        //放入session中,也可以存入redis
        session.setAttribute("kaptcha",text);
        System.out.println("=====================>存入session的验证码"+text);
        //生成图片
        BufferedImage image = producer.createImage(text);
        FastByteArrayOutputStream fastByteArrayOutputStream = new FastByteArrayOutputStream();
        ImageIO.write(image,"jpg",fastByteArrayOutputStream);
        //返回base64
        return Base64.getEncoder().encodeToString(fastByteArrayOutputStream.toByteArray());
    }
}

图片格式

@GetMapping("/code11")
    public void getVerifyCode111(HttpServletResponse response, HttpSession session) throws IOException {
        //生成验证码
        String text = producer.createText();
        //放入session中,也可以存入redis
        session.setAttribute("kaptcha",text);
        System.out.println("=====================>存入session的验证码"+text);
        //生成图片
        BufferedImage image = producer.createImage(text);
        response.setContentType("image/png");
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"jpg",outputStream);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值