Google验证码生成

项目配置: .ymi

project:
  # 验证码类型 math 数组计算 char 字符验证
  captchaType: math

Controller层

public class CaptchaController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    // 验证码类型
    @Value("${project.captchaType}")
    private String captchaType;

    /**
     * 生成验证码
     */
    //@ApiOperation("生成验证码")
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        AjaxResult ajax = AjaxResult.success();
        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }
}

Redis配置类

 * spring redis 工具类
 *
 * 
 **/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCache
{
    @Autowired
    public RedisTemplate redisTemplate;

       /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
    {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
你可以使用 Spring Boot 来生成验证码。以下是一个简单的示例: 1. 首先,添加以下依赖到你的 `pom.xml` 文件中: ```xml <dependencies> <!-- Spring Boot Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Boot Thymeleaf (如果你希望使用 Thymeleaf 模板引擎) --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- Google Guava (用于生成随机字符串) --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>30.1-jre</version> </dependency> </dependencies> ``` 2. 创建一个验证码生成器类,例如 `CaptchaGenerator`: ```java import com.google.common.base.Strings; import com.google.common.hash.Hashing; public class CaptchaGenerator { private static final int CAPTCHA_LENGTH = 6; public static String generateCaptcha() { String captcha = ""; while (Strings.isNullOrEmpty(captcha) || captcha.length() != CAPTCHA_LENGTH) { captcha = Hashing.sha256() .hashString(String.valueOf(Math.random()), Charsets.UTF_8) .toString() .replaceAll("[^0-9]", "") .substring(0, CAPTCHA_LENGTH); } return captcha; } } ``` 3. 创建一个 Spring Boot 控制器类,例如 `CaptchaController`: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class CaptchaController { @GetMapping("/captcha") public String getCaptcha() { return CaptchaGenerator.generateCaptcha(); } } ``` 4. 运行你的 Spring Boot 应用,并访问 `/captcha` 路径即可获取生成验证码。 这只是一个简单的示例,你可以根据自己的需求进行修改和扩展。验证码生成器使用了 Google Guava 库来生成随机字符串,你也可以使用其他方法来生成验证码。同时,你还可以添加额外的逻辑来处理验证码的验证等功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Cherish Xin And Meng

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

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

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

打赏作者

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

抵扣说明:

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

余额充值