SpringBoot中使用kaptcha依赖实现图片验证码生成及校验

1.SpringBoot中集成kaptcha

        <!-- 引入图形验证码依赖 -->
        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>

2.编写kaptcha配置类KaptchaConfig

package com.sanxia.config;

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

//kaptcha配置类
@Component
public class KaptchaConfig {
    @Bean
    public DefaultKaptcha getDefaultKaptcha() {
        com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();
        Properties properties = new Properties();
        // 图片边框
        properties.setProperty("kaptcha.border", "yes");
        // 边框颜色
        properties.setProperty("kaptcha.border.color", "105,179,90");
        // 字体颜色
        properties.setProperty("kaptcha.textproducer.font.color", "red");
        // 图片宽
        properties.setProperty("kaptcha.image.width", "135");
        // 图片高
        properties.setProperty("kaptcha.image.height", "50");
        //使用哪些字符生成验证码
        properties.setProperty("kaptcha.textproducer.char.string", "ACEHKTW247");
        // 字体大小
        properties.setProperty("kaptcha.textproducer.font.size", "43");
        // session key
        properties.setProperty("kaptcha.session.key", "code");
        // 验证码长度
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        // 字体
        properties.setProperty("kaptcha.textproducer.font.names", "Arial");
        //干扰线颜色
        properties.setProperty("kaptcha.noise.color", "red");

        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);

        return defaultKaptcha;
    }
}

3.编写kaptcha的控制层代码KaptchaController

3.1.生成验证码接口为"/kaptcha/create",请求方式为get,校验验证码接口为"/kaptcha/check",传递参数为"picCode",请求方式为post

package com.sanxia.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import org.apache.commons.lang3.StringUtils;
import com.sanxia.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

//谷歌的图形验证码模块,使用参考网站https://zhuanlan.zhihu.com/p/68068636
//kaptcha,控制层代码实现
//@Api(tags = {"Google-kaptcha验证码"})
@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {

    @Autowired
    DefaultKaptcha defaultKaptcha;

    //    @ApiOperation(value = "生成验证码")
    @GetMapping("/create")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // 生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute("picCode", createText);
            // 使用生成的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    //    @ApiOperation(value = "校对验证码")
    @PostMapping("/check")
    public Result checkVerificationCode(@RequestParam String picCode, HttpServletRequest httpServletRequest) {
        String verificationCodeIn = (String)httpServletRequest.getSession().getAttribute("picCode");
        httpServletRequest.getSession().removeAttribute("picCode");
        if ((StringUtils.isEmpty(verificationCodeIn)) || (!verificationCodeIn.equals(picCode))) {
            return Result.fail("验证码错误,或已失效");
        } else {
            return Result.success(200, "验证码输入正确,校验通过", "");
        }
    }
}

4.前端HTML代码

<div>
<img id="verificationCodeImg" src="http://localhost:8080/kaptcha/create" style="cursor: pointer;" title="点击生成图形验证码" />
</div>
<script type="text/javascript" >
$(function () {
    // 刷新验证码
    $("#verificationCodeImg").bind("click", function () {
        $(this).hide().attr('src', 'http://localhost:8080/kaptcha/create?').fadeIn();
    });
});
</script>

5.试验

5.1.生成验证码

5.2.校验验证码

5.2.1.正确输入

5.2.2.错误输入

 

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Kaptcha是一个Google开源的图片验证码生成工具,可以根据属性来设置自己想要的基本意义上的验证码。在前端,可以通过获取验证码图片对用户输入的验证码进行简单的规则校验返回登录结果,并提供刷新验证码的动作,防止出现用户难以辨识的识别码。在SpringBoot,可以通过导入依赖和配置KaptchaConfig来集成创建验证码工具。具体步骤如下: 1. 导入POM依赖:在pom.xml文件添加以下依赖: <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency> 2. 配置KaptchaConfig:在配置类添加以下代码: @Bean public DefaultKaptcha producer() { Properties properties = new Properties(); // 设置验证码图片的宽度 properties.setProperty("kaptcha.image.width", "150"); // 设置验证码图片的高度 properties.setProperty("kaptcha.image.height", "50"); // 设置验证码字符的长度 properties.setProperty("kaptcha.textproducer.char.length", "4"); // 设置验证码字符的范围 properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); // 设置验证码字体的大小 properties.setProperty("kaptcha.textproducer.font.size", "30"); // 设置验证码字体的颜色 properties.setProperty("kaptcha.textproducer.font.color", "black"); // 设置验证码噪点的颜色 properties.setProperty("kaptcha.noise.color", "black"); // 设置验证码噪点的生成方式 properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise"); // 设置验证码样式 properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.ShadowGimpy"); Config config = new Config(properties); DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); defaultKaptcha.setConfig(config); return defaultKaptcha; } 3. 在前端页面添加验证码输入框和图片:在验证码输入框后面添加以下代码: <span> <input type="text" id="code" name="tryCode" placeholder="VerfiCode">  <img alt="验证码" onclick="this.src='/kaptcha?d='+new Date()*1" th:src="@{./kaptcha}"/> </span>

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值