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

2022-11-13 13:11:24 功能 整合 验证码

栗子

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

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

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

配置文件

SpringBoot项目中pom.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

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

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

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

 // 文字个数
 properties.put("kaptcha.textproducer.char.space", "7");

2、获取图片

 @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、演示一下

后台打印:

访问链接:

到此这篇关于SpringBoot整合kaptcha实现图片验证码功能的文章就介绍到这了,更多相关SpringBoot整合kaptcha内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章