Spring Boot利用Kaptcha生成验证码

时间:2024-02-22 08:00:08

生成验证码

我们在登录或注册某个网站的时候,会需要我们输入验证码,才能登录注册,那么如何生成验证码呢?其实,生成验证码我们可以用Java Swing在后台内存里的区域画一个出来,但是非常麻烦,所以我们选择一些现成的工具——Kaptcha,接下来就看看如何使用这个工具在内存中画出一个验证码(图片),怎么把他发送给浏览器,浏览器怎么显示在登陆页面的位置。

kaptcha

kaptcha 是Google开源的非常实用的自动生成验证码的一个工具,有了它,你可以生成各种样式的验证码。并且使用Kaptcha 生成验证码也十分简单,只需添加jar包,然后配置一下就可以使用。在配置中,可以自己定义验证码字体的大小、颜色、样式;验证码图片的大小、边框、背景;验证码的内容范围;验证码的干扰线等等。

Kaptcha在Spring Boot中的使用

Kaptcha

  • 导入jar包
  • 编写Kaptcha配置类
  • 生成随机字符、生成图片

1. 在pom文件中导入jar包

<!-- Kaptcha Google验证码工具-->
<dependency>
	<groupId>com.github.penggle</groupId>
	<artifactId>kaptcha</artifactId>
	<version>2.3.2</version>
</dependency>

2. Kaptcha配置类

@Configuration
public class KaptchaConfig {

    @Bean
    public Producer kaptchaProducer() {
        Properties properties = new Properties();
        properties.setProperty("kaptcha.image.width","135");
        properties.setProperty("kaptcha.image.height","55");
        properties.setProperty("kaptcha.textproducer.font.size","32");
        properties.setProperty("kaptcha.textproducer.font.color","0,0,0");
        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. 生成随机字符串、生成图片

在生成验证码之前,我们先看看Kaptcha的核心

在这里插入图片描述
主要就是Producer接口,这个接口中有两个方法,分别是创建验证码图片和生成随机验证码。

编写controller层代码,返回验证码图片并将验证码保存在session中,在用户登录时验证。

/**
* 获取验证码的方法
*/
@GetMapping("kaptcha")
public void getKaptcha(HttpServletResponse response, HttpSession session) {
    // 生成验证码
    String text = kaptchaProducer.createText();
    // 生成图片
    BufferedImage image = kaptchaProducer.createImage(text);

    // 将验证码存入session
    session.setAttribute("kaptcha",text);
    // 将图片输出给浏览器
    response.setContentType("image/png");
    try {
        OutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"png",outputStream);
    } catch (IOException e) {
        logger.error("响应验证码失败:"+ e.getMessage());
    }
}

在这里插入图片描述

4. JavaScript

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