Kaptcha——图片验证码生成工具

1. 介绍与使用

1.1 Kapcha是什么

Kaptcha 是一个Google开源、可自由配置的图片验证码生成工具,可以根据属性来设置自己想要的基本意义上的验证码

对于前端后端

后端:

  • 随机生成四位数字的验证码图片和数字
  • 结合随机生成的UUID作为Key,验证码值作为Value保存验证码到Redis中
  • 将UUID和验证码图片响应给用户,等用户提交后验证校验码是否有效

前端:

  • 进入登录/注册页面时,获取验证码图片
  • 对用户输入的验证码进行简单的规则校验
  • 返回登录结果
  • 提供刷新验证码的动作,防止出现用户难以辨识的识别码

1.2 基本使用步骤

  1. 导入POM依赖
  2. 定义生成验证码图片时的一系列参数:图片的宽高、字符内容、干扰类型等
  3. 调用com.google.code.kaptcha.impl.DefaultKaptcha#createText()创建验证码值
  4. 调用com.google.code.kaptcha.impl.DefaultKaptcha#createText(kaptchaText)创建验证图片(BufferedImage)
  5. 将图片BufferedImage转换为目标

2. SpringBoot集成创建验证码工具

2.1 导入依赖

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

2.2 验证码的配置 KaptchaConfig

对于kaptcha来说,它是图片验证码,因此要配置图片的基本参数:

  1. 首先,它本质是一张图片,所以将会涉及图片的边框、宽高、背景颜色
  2. 验证码是字符,这将会涉及到字体类型、字体大小、字体颜色、字体间距、字体数量
  3. 验证码的另一个重要功能是干扰,这将会涉及干扰类型、干扰样式(干扰的意思是要存在一些阻碍让用户看的不方便)
/**
 * 验证码的配置
 */
@Configuration
public class KaptchaConfig {

    @Bean
    public DefaultKaptcha getDefaultKaptcha(){
        //创建一个验证码的实例
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        //创建属性的实例
        Properties properties = new Properties();
        //设置属性
        //设置边框
        properties.setProperty("kaptcha.border","no");
        /*//设置边框的颜色
        properties.setProperty("kaptcha.border.color","white");*/
        //设置背景颜色
        //背景颜色渐变开始
        properties.setProperty("kaptcha.background.clear.from","white");
        //背景颜色渐变结束
        properties.setProperty("kaptcha.background.clear.to","white");
        //字体颜色
        properties.setProperty("kaptcha.textproducer.font.color","blue");
        //文字间隔
        properties.setProperty("kaptcha.textproducer.char.space","10");
        //设置验证码的长度
        properties.setProperty("kaptcha.textproducer.char.length","4");
        //设置图片的宽度
        properties.setProperty("kaptcha.image.width","130");
        //设置图片的高度
        properties.setProperty("kaptcha.image.height","50");
        //设置字体样式
        properties.setProperty("kaptcha.textproducer.font.names","宋体");
        //设置字符串,验证码就是从这里面产生
        properties.setProperty("kaptcha.textproducer.char.string","0123456789abcdefghijklmn");
        //设置干扰线
        properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");
        //设置字体大小
        properties.setProperty("kaptcha.textproducer.font.size","35");
        //将properties包装到配置中
        Config config = new Config(properties);
        //将配置设置到创建的验证码实例defaultKaptcha
        defaultKaptcha.setConfig(config);
        //返回
        return defaultKaptcha;
    }
}

2.3 验证码生成管理器 KaptchaProducerController

@RestController
public class KaptchaProduceController {
    //首先将验证码工具导入
    @Autowired
    DefaultKaptcha defaultKaptcha;
    /**
     * 生成验证码
     *
     * @param request
     * @param response
     * @throws Exception
     */

    @GetMapping("/kaptcha")
    public void getKaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //设置响应头
        //设置响应头中的Cache-Control字段为no-cache,告诉浏览器不要缓存响应内容。
        response.setHeader("Cache-Control", "no-cache");
        //用于将“Pragma”HTTP响应标头的值设置为“无缓存”,“Pragma”标头由服务器用于指定客户端或中间代理中的缓存机制的指令。
        response.setHeader("Pragma", "no-cache");
        //设置响应内容类型为JPEG图像
        response.setContentType("image/jpeg");
        //创建验证码
        String text = defaultKaptcha.createText();
        HttpSession session = request.getSession();
        //将验证码存入session
        session.setAttribute("rightcode", text);
        //创建验证码图片,BufferedImage可以用于生成图像
        BufferedImage image = defaultKaptcha.createImage(text);
        //创建一个响应输出流
        ServletOutputStream os = response.getOutputStream();
        //将生成的图像写入响应输出流中
        ImageIO.write(image, "jpg", os);
        //而不会引发任何异常。如果指定的对象为null或在关闭它时发生异常,
        // 则该方法将忽略它并继续执行,而不会引发任何进一步的异常。
        IOUtils.closeQuietly(os);
    }
}

2.4 登录进行验证

/**
 * 登录控制器
 * ------李硕
 */
@Slf4j
@Controller
public class LoginController {

    @Resource
    UserService userService;

    /**
     *
     * @param username 账户
     * @param password 密码
     * @param trycode  验证码
     * @param session  储存对象
     * @return
     */
    @RequestMapping(value = "/user/login")
    public ModelAndView login(@RequestParam("username") String username,
                              @RequestParam("password") String password,
                              @RequestParam("tryCode") String trycode,
                              HttpSession session){
        ModelAndView modelAndView = new ModelAndView();
        //获取session中存储的trycode对象
        String rightcode= (String) session.getAttribute("rightcode");
        //userService.Login()方法是我创建的一个在数据库搜索数据的一个方法
        //搜索数据库中的数据,看是否存在所登录用户的信息
        Userbean userbean = userService.Login(username, password);
        //打印输出对象
        log.info("username:{}",username);
        log.info("password:{}",password);
        log.info("code:{}",trycode);
        if (userbean!=null && rightcode.equals(trycode)) {
            modelAndView.setViewName("shopping.html");
            return modelAndView;
        }
        else{
            modelAndView.addObject("msg","用户名或密码或验证码有误");
            modelAndView.setViewName("login.html");
            return modelAndView;
        }
    }
}

2.5 html页面以及函数调用(注意thymeleaf语法)

把这一部分放在验证码输入框后面

<span>
<input type="text" id="code" name="tryCode" placeholder="VerfiCode">&nbsp;
<img alt="验证码" onclick="this.src='/kaptcha?d='+new Date()*1" th:src="@{./kaptcha}"/>
</span>
  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 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
发出的红包

打赏作者

LD白哥

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

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

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

打赏作者

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

抵扣说明:

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

余额充值