SpringBoot整合Kaptcha实现图片验证码加减乘除


SpringBoot整合Kaptcha实现图片验证码加减乘除

在开发Web应用时,验证码是一个常见的功能,它可以帮助我们防止机器人的恶意操作。今天我们将学习如何使用Kaptcha生成图片验证码,并自定义验证码内容为100以内的加减乘除运算。

1. 添加Kaptcha依赖

首先,确保你的项目中包含Kaptcha的依赖。对于Maven项目,可以在pom.xml中添加以下依赖:

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

2. 自定义文本生成器

我们需要创建一个自定义的文本生成器MathKaptchaTextCreator,它将生成包含加减乘除运算的验证码内容。

package com.bangbang.tracesource.admin.conf;

import com.google.code.kaptcha.text.impl.DefaultTextCreator;

import java.util.Random;

public class MathKaptchaTextCreator extends DefaultTextCreator {
    @Override
    public String getText() {
        Random random = new Random();
        int x = random.nextInt(100);
        int y = random.nextInt(100);
        String[] operators = {"+", "-", "*", "/"};
        String operator = operators[random.nextInt(4)];
        String expression = x + operator + y;
        int result = 0;
        switch (operator) {
            case "+":
                result = x + y;
                break;
            case "-":
                result = x - y;
                break;
            case "*":
                result = x * y;
                break;
            case "/":
                result = y == 0 ? x : x / y;
                break;
        }
        return expression + "=?@" + result;
    }
}

在这个实现中,我们生成了一个随机的加减乘除运算表达式,并将其结果附加在表达式的末尾,以@分隔。例如:1+1=?@2

3. 配置Kaptcha

接下来,创建一个配置类KaptchaConfig来配置Kaptcha的属性,并指定我们的自定义文本生成器。

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Properties;

@Component
public class KaptchaConfig {
    @Bean
    public DefaultKaptcha getDefaultKaptcha() {
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", "yes");
        properties.setProperty("kaptcha.border.color", "105,179,90");
        properties.setProperty("kaptcha.textproducer.font.color", "black");
        properties.setProperty("kaptcha.image.width", "110");
        properties.setProperty("kaptcha.image.height", "40");
        properties.setProperty("kaptcha.textproducer.font.size", "35");
        properties.setProperty("kaptcha.session.key", "code");
        properties.setProperty("kaptcha.textproducer.impl", "com.shy.admin.conf.MathKaptchaTextCreator");
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        // 设置干扰线
        properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.FishEyeGimpy");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

4. 获取验证码图片的方法

我们还需要一个控制器方法来生成和返回验证码图片。

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class KaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @RequestMapping(value = "/kaptcha", method = RequestMethod.GET)
    public void getKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws IOException {
        byte[] captchaChallengeAsJpeg;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // 生产验证码字符串并保存到session中 eg: 3-2=?@1
            String createText = defaultKaptcha.createText();
            // capStr就是算术题 也就是用户看到的验证码
            String capStr = createText.substring(0, createText.lastIndexOf("@"));
            // code 就是算术的结果 也就是输入的验证码
            String code = createText.substring(createText.lastIndexOf("@") + 1);
            httpServletRequest.getSession().setAttribute("KAPTCHA_SESSION_KEY", code);
            // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(capStr);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        httpServletResponse.getOutputStream().write(captchaChallengeAsJpeg);
        httpServletResponse.getOutputStream().flush();
    }
}

4.1. 详细讲解控制器中的切割操作

在控制器方法中,我们生成了验证码文本并将其保存在session中。生成的验证码文本格式为:1+1=?@2。接下来,我们需要将表达式和结果分离开来,以便将结果保存在session中用于验证用户输入。

// 生产验证码字符串并保存到session中 eg: 3-2=?@1
String createText = defaultKaptcha.createText();
// capStr就是算术题 也就是用户看到的验证码
String capStr = createText.substring(0, createText.lastIndexOf("@"));
// code 就是算术的结果 也就是输入的验证码
String code = createText.substring(createText.lastIndexOf("@") + 1);
httpServletRequest.getSession().setAttribute("KAPTCHA_SESSION_KEY", code);

在这段代码中:

  1. createText = defaultKaptcha.createText();:生成验证码文本,例如:1+1=?@2
  2. capStr = createText.substring(0, createText.lastIndexOf("@"));:获取运算表达式部分,即1+1=?
  3. code = createText.substring(createText.lastIndexOf("@") + 1);:获取运算结果部分,即2
  4. httpServletRequest.getSession().setAttribute("KAPTCHA_SESSION_KEY", code);:将运算结果保存到session中,用于后续的验证。

通过这种方式,我们可以将验证码的运算表达式和结果分离开来,用户看到的是表达式部分,而验证时使用的是结果部分。

生成的验证码如下图所示:
在这里插入图片描述

5. 总结

通过上述步骤,我们实现了一个自定义的Kaptcha图片验证码生成器,该生成器可以生成包含100以内的加减乘除运算的验证码。通过这种方式,我们不仅可以提高验证码的安全性,还能增强用户体验。

希望这篇博客对你有所帮助!如果有任何问题或建议,欢迎在评论区留言。

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot整合Kaptcha,你可以按照以下步骤进行操作: 步骤1:添加Kaptcha依赖 在你的Spring Boot项目的pom.xml文件中,添加Kaptcha的依赖: ```xml <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency> ``` 步骤2:配置Kaptcha 在application.properties(或application.yml)文件中,添加以下配置: ```properties # Kaptcha Configurations kaptcha.border = no kaptcha.border.color = black kaptcha.textproducer.font.color = black kaptcha.image.width = 150 kaptcha.image.height = 50 kaptcha.textproducer.char.string = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 kaptcha.textproducer.char.length = 4 kaptcha.noise.impl = com.google.code.kaptcha.impl.NoNoise kaptcha.background.clear.from = white kaptcha.background.clear.to = white kaptcha.textproducer.font.size = 40 ``` 步骤3:创建验证码接口 在你的控制器中创建一个用于生成验证码图片的接口,例如: ```java @RestController public class CaptchaController { @GetMapping("/captcha") public void getCaptcha(HttpServletRequest request, HttpServletResponse response) { // 创建DefaultKaptcha对象并配置参数 DefaultKaptcha kaptcha = new DefaultKaptcha(); Properties properties = new Properties(); properties.setProperty("kaptcha.border", "no"); properties.setProperty("kaptcha.textproducer.font.color", "black"); kaptcha.setConfig(new Config(properties)); // 生成验证码文本 String text = kaptcha.createText(); // 将验证码文本保存到session中 request.getSession().setAttribute("captcha", text); // 创建验证码图片并输出到response中 BufferedImage image = kaptcha.createImage(text); try { OutputStream out = response.getOutputStream(); ImageIO.write(image, "jpg", out); out.flush(); } catch (IOException e) { e.printStackTrace();

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shy好好学习

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值