SpringBoot整合kaptcha实现图片验证码功能

举个栗子🌰

登录是所有系统都绕不开的一道坎,很多系统会在用户名和密码下发放置一个图形验证码,例如:

这些图形验证码看起来不仅很丑,而且模糊,但却是保护系统的第一道屏障,它的作用是:设计的初衷其实就是为了防自动化,防止一些人利用自动工具恶意攻击网站,比如批量注册,撑爆你的数据库

实现这个功能并不复杂,但是为了不让大家重复造轮子,这里我给大家推荐一个现成的轮子:kaptcha,使用起来非常简单,废话不多说直接上代码。

尝试一下🍰

配置文件

SpringBoot项目中pom.xml文件

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>SpringBoot-VerifyCode</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBoot-VerifyCode</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

		<!-- 验证码生成包 -->
        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

项目代码

项目结构

SpringBootVerifyCodeApplication.java

java 复制代码
package com.example.springbootverifycode;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootVerifyCodeApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootVerifyCodeApplication.class, args);
    }

}

VerifyCodeConfig.java

java 复制代码
package com.example.springbootverifycode.config;

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

import java.util.Properties;

@Configuration
public class VerifyCodeConfig {

    @Bean
    Producer producer() {
        Properties properties = new Properties();
        //设置图片边框
        properties.setProperty("kaptcha.border", "yes");
        //设置图片边框为蓝色
        properties.setProperty("kaptcha.border.color", "blue");
        //背景颜色渐变开始
        properties.put("kaptcha.background.clear.from", "127,255,212");
        //背景颜色渐变结束
        properties.put("kaptcha.background.clear.to", "240,255,255");
        // 字体颜色
        properties.put("kaptcha.textproducer.font.color", "black");
        // 文字间隔
        properties.put("kaptcha.textproducer.char.space", "10");
        //如果需要去掉干扰线
		properties.put("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");
        // 字体
        properties.put("kaptcha.textproducer.font.names", "Arial,Courier,cmr10,宋体,楷体,微软雅黑");
        // 图片宽度
        properties.setProperty("kaptcha.image.width", "200");
        // 图片高度
        properties.setProperty("kaptcha.image.height", "50");
        // 从哪些字符中产生
        properties.setProperty("kaptcha.textproducer.char.string", "0123456789abcdefghijklmnopqrsduvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
        // 字符个数
        properties.setProperty("kaptcha.textproducer.char.length", "6");
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(new Config(properties));
        return defaultKaptcha;
    }
}

KaptchaController.java

java 复制代码
package com.example.springbootverifycode.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class KaptchaController {

    @Autowired
    private Producer producer;

    @GetMapping("/getVerifyCode")
    public void getVerifyCode(HttpServletResponse response, HttpSession session) throws IOException {
        response.setContentType("image/jpeg");
        String text = producer.createText();
        session.setAttribute("vf", text);
        BufferedImage image = producer.createImage(text);
        try (ServletOutputStream sos = response.getOutputStream()) {
            ImageIO.write(image, "jpg", sos);
        }
    }
}

测试一下

生成运算符验证码

1、设置字符个数为7

java 复制代码
 // 文字个数
 properties.put("kaptcha.textproducer.char.space", "7");

2、获取图片

java 复制代码
 @GetMapping("/getCal")
    public void getCal(HttpServletResponse response, HttpSession session) throws IOException {
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        System.out.println("当前生成的字符串为:" + text);
        //个位数字相加
        String s1 = text.substring(0, 2);
        String s2 = text.substring(2, 4);
        int count = Integer.valueOf(s1).intValue() + Integer.valueOf(s2).intValue();
        System.out.println("计算结果为:" + count);
        //生成图片验证码
        BufferedImage image = producer.createImage(s1 + "+" + s2 + "=?");
        try (ServletOutputStream sos = response.getOutputStream()) {
            ImageIO.write(image, "jpg", sos);
        }
    }

3、演示一下

后台打印:

访问链接:

相关推荐
程序员爱钓鱼17 分钟前
Python编程实战 | 函数与模块化编程 - 第三方库的安装与管理(pip使用)
后端·python·ipython
程序员爱钓鱼19 分钟前
Python编程实战 | 面向对象与进阶语法-类与对象的概念
后端·python·ipython
IT_陈寒1 小时前
Redis性能翻倍的5个冷门技巧,90%的开发者都不知道第3个!
前端·人工智能·后端
噔噔噔噔@1 小时前
软件测试面试的排序算法问题如何回答
面试·职场和发展·排序算法
雨中散步撒哈拉1 小时前
14、做中学 | 初二上期 Golang集合Map
开发语言·后端·golang
陈老师还在写代码1 小时前
springboot 打包出来的 jar 包的名字是在哪儿决定的
spring boot·后端·jar
m0_564264188 小时前
IDEA DEBUG调试时如何获取 MyBatis-Plus 动态拼接的 SQL?
java·数据库·spring boot·sql·mybatis·debug·mybatis-plus
꒰ঌ 安卓开发໒꒱10 小时前
RabbitMQ面试全解析:从核心概念到高可用架构
面试·架构·rabbitmq
熊小猿10 小时前
在 Spring Boot 项目中使用分页插件的两种常见方式
java·spring boot·后端
paopaokaka_luck10 小时前
基于SpringBoot+Vue的助农扶贫平台(AI问答、WebSocket实时聊天、快递物流API、协同过滤算法、Echarts图形化分析、分享链接到微博)
java·vue.js·spring boot·后端·websocket·spring