SpringBoot集成Kaptcha验证码生成器快速入门Demo

目录

1. 概述

2. 快速入门

2.1 创建工程

2.2 导入依赖

2.3 添加配置文件

2.4 添加验证码工具类

2.5 创建Kaptcha配置类

2.6 添加控制类

2.7 创建启动类

2.8 创建测试页面

 3.  Demo下载地址


1. 概述

        验证码(CAPTCHA):是 Completely Automated Public Turing test to tell Computers and Humans Apart(全自动区分计算机和人类的图灵测试)的缩写,是一种区分用户是计算机还是人的公共全自动程序。

        作用:可以防止恶意破解密码、刷票、论坛灌水,有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登录尝试,实际上用验证码是现在很多网站通行的方式,我们利用比较简易的方式实现了这个功能。

        这个问题可以由计算机生成并评判,但是必须只有人类才能解答。由于计算机无法解答 CAPTCHA 的问题,所以回答出问题的用户就可以被认为是人类。

        Kaptcha是谷歌放在github上的一个验证码 jar 包,是一个基于SimpleCaptcha的验证码开源项目,我们可以简单配置属性就可以实现验证码的验证功能。

        它能够实现以下效果:水纹有干扰、鱼眼无干扰、水纹无干扰、阴影无干扰、阴影有干扰

        其中,它们的文字内容限制、背景图片、文字颜色、大小、干扰样式颜色、整体(图片)高度、宽度、图片渲染效果、干扰与否都是可以进行自定义的。

Constant

描述

默认值

kaptcha.border

图片边框,合法值:yes, no

yes

kaptcha.border.color

边框颜色,合法值:r,g,b (and optional alpha) 或者 white,black,blue.

black

kaptcha.border.thickness

边框厚度,合法值:>0

1

kaptcha.image.width

图片宽

200

kaptcha.image.height

图片高

50

kaptcha.producer.impl

图片实现类

com.google.code.kaptcha.impl.DefaultKaptcha

kaptcha.textproducer.impl

文本实现类

com.google.code.kaptcha.text.impl.DefaultTextCreator

kaptcha.textproducer.char.string

文本集合,验证码值从此集合中获取

abcde2345678gfynmnpwx

kaptcha.textproducer.char.length

验证码长度

5

kaptcha.textproducer.font.names

字体

Arial, Courier

kaptcha.textproducer.font.size

字体大小

40px.

kaptcha.textproducer.font.color

字体颜色,合法值:r,g,b 或者 white,black,blue.

black

kaptcha.textproducer.char.space

文字间隔

2

kaptcha.noise.impl

干扰实现类

com.google.code.kaptcha.impl.DefaultNoise

kaptcha.noise.color

干扰线颜色,合法值:r,g,b 或者 white,black,blue.

black

kaptcha.obscurificator.impl

图片样式: 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy

com.google.code.kaptcha.impl.WaterRipple

kaptcha.background.impl

背景实现类

com.google.code.kaptcha.impl.DefaultBackground

kaptcha.background.clear.from

背景颜色渐变,开始颜色

light grey

kaptcha.background.clear.to

背景颜色渐变, 结束颜色

white

kaptcha.word.impl

文字渲染器

com.google.code.kaptcha.text.impl.DefaultWordRenderer

kaptcha.session.key

session key

KAPTCHA_SESSION_KEY

kaptcha.session.date

session date

KAPTCHA_SESSION_DATE

2. 快速入门

2.1 创建工程

         

        设置Maven

        设置自动导入包 Auto Import

        设置启动注解 Annotation Processors

2.2 导入依赖

<!--引入springboot依赖-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.4.RELEASE</version>
</parent>

<dependencies>
    <!--引入spring-boot启动器依赖, 添加启动器后web工程常用的依赖会自动帮你引入-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--test-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!--lombok-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <!-- Thymeleaf 依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <!-- Kaptcha 依赖(验证码) -->
    <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>

2.3 添加配置文件

        resources\application.yml 当中 添加配置信息

# 项目配置
server:
  port: 8888

# Spring 配置
spring:
  # Thymeleaf 配置
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    cache: false

# 验证码配置
kaptcha:
  border: "no"             # 是否有边框,默认为 yes,可选 yes、no
  border.color: 105,179,90 # 边框颜色
  textproducer:
    font:
      color: blue          # 验证码字体颜色
      size: 30             # 文本字符大小
      names: 宋体,楷体      # 文本字体样式
    char:
      length: 4            # 验证码文本字符长度
  image:
    width: 120             # 图片宽度
    height: 40             # 图片高度
  session:
    key: code              # 存储 session key

2.4 添加验证码工具类

package com.miaxis.util;

import com.google.code.kaptcha.Constants;
import javax.servlet.http.HttpSession;

/**
 * 验证码 工具类
 */
public class CodeUtil {
    /**
     * 验证码校验
     * @param session
     *        key
     * @return
     */
    public static boolean checkVerifyCode(HttpSession session, String key) {
        // 获取生成的验证码
        String verifyCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        System.out.println("verifyCode: " + verifyCode);
        // 获取用户输入的验证码
        if (key == null || !key.equals(verifyCode)) {
            return false;
        }
        return true;
    }
}

2.5 创建Kaptcha配置类

package com.miaxis.config;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;

/**
 * Kaptcha配置类
 *     用于生成图形验证码
 */
@Configuration
public class KaptchaConfig {
    /**
     * 边框
     */
    @Value("${kaptcha.border}")
    private String border;

    /**
     * 边框颜色
     */
    @Value("${kaptcha.border.color}")
    private String borderColor;

    /**
     * 字体颜色
     */
    @Value("${kaptcha.textproducer.font.color}")
    private String textproducerFontColor;

    /**
     * 字体大小
     */
    @Value("${kaptcha.textproducer.font.size}")
    private String textproducerFontSize;

    /**
     * 字体样式
     */
    @Value("${kaptcha.textproducer.font.names}")
    private String textproducerFontNames;

    /**
     * 验证码长度
     */
    @Value("${kaptcha.textproducer.char.length}")
    private String textproducerCharLength;

    /**
     * 图片宽度
     */
    @Value("${kaptcha.image.width}")
    private String imageWidth;

    /**
     * 图片高度
     */
    @Value("${kaptcha.image.height}")
    private String imageHeight;

    /**
     * 存储的 Session Key
     */
    @Value("${kaptcha.session.key}")
    private String sessionKey;

    /**
     * 配置 Kapcha 参数
     * @return
     */
    @Bean
    public DefaultKaptcha getDefaultKapcha() {
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", border);
        properties.setProperty("kaptcha.border.color", borderColor);
        properties.setProperty("kaptcha.textproducer.font.color", textproducerFontColor);
        properties.setProperty("kaptcha.textproducer.font.size", textproducerFontSize);
        properties.setProperty("kaptcha.textproducer.font.names", textproducerFontNames);
        properties.setProperty("kaptcha.textproducer.char.length", textproducerCharLength);
        properties.setProperty("kaptcha.image.width", imageWidth);
        properties.setProperty("kaptcha.image.height", imageHeight);
        properties.setProperty("kaptcha.session.key", sessionKey);
        //图片的干扰样式:默认存在无规则划线干扰
        //无干扰:com.google.code.kaptcha.impl.NoNoise
        //properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");
        //图片干扰颜色:默认为黑色
        properties.setProperty("kaptcha.noise.color", "black");
        //图片渲染效果:默认水纹
        // 水纹com.google.code.kaptcha.impl.WaterRipple
        // 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy
        // 阴影com.google.code.kaptcha.impl.ShadowGimpy
        properties.setProperty("kaptcha.obscurificator.impl",
                "com.google.code.kaptcha.impl.ShadowGimpy");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }

}

2.6 添加控制类

package com.miaxis.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.miaxis.util.CodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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;

/**
 * 图片 控制器
 */
@Controller
public class ImgController {
    /**
     * Kaptcha 配置
     */
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    /**
     * 跳转到验证码页面
     * @return
     */
    @GetMapping("/codeHtml")
    public String code() {
        return "code";
    }

    /**
     * 验证码
     * @return
     * @throws IOException
     */
    @GetMapping("/code")
    public void defaultKaptcha(HttpSession session, HttpServletResponse response) {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        // 生成验证码字符串并保存到 session 中
        String capText = defaultKaptcha.createText();
        System.out.println("capText: " + capText);
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

        // 向客户端写出
        BufferedImage bi = defaultKaptcha.createImage(capText);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            ImageIO.write(bi, "jpg", out);
            out.flush();
        } catch (IOException e) {
            System.err.println("输出图形验证码失败");
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 测试验证码是否正确
     * @param session
     * @param code
     * @return
     */
    @ResponseBody
    @PostMapping("/login")
    public String login(HttpSession session, String code) {
        System.out.println("code: " + code);
        if (!CodeUtil.checkVerifyCode(session, code)) {
            return "验证码错误!";
        } else {
            return "验证码正确!";
        }
    }
}

2.7 创建启动类

package com.miaxis;

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

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

2.8 创建测试页面

        resources 中 添加测试页面 resources\templates\code.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>
<body>
<form action="/login" method="post">
    <input type="text" name="code"><img src="/code">
    <input type="submit" value="提交">
</form>
</body>
</html>

        测试: http://localhost:8888/codeHtml

 3.  Demo下载地址

编译器版本:IntelliJ IDEA 2020.3.2 x64

JDK版本:java 1.8.0_111

下载地址:https://download.csdn.net/download/mickey2007/89110819

好的,我可以为您提供制作验证码的步骤: 1. 添加依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>com.github.axet</groupId> <artifactId>kaptcha</artifactId> <version>0.0.9</version> </dependency> ``` 2. 配置 Kaptcha 在 application.properties 或 application.yml 文件中添加以下配置: ```yaml kaptcha: border: no border.color: black textproducer.font.color: black textproducer.char.length: 4 noise.impl: com.github.axet.kaptcha.impl.DefaultNoise noise.color: black ``` 这些配置项可以根据实际需求进行修改。 3. 生成验证码 在控制器中添加以下代码: ```java @GetMapping("/captcha.jpg") public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception { // 创建 Kaptcha 对象 ConfigurableKaptcha kaptcha = new ConfigurableKaptcha(); // 生成验证码 String code = kaptcha.createText(); // 将验证码存入 Session request.getSession().setAttribute("captcha", code); // 将验证码输出到页面 response.setContentType("image/jpeg"); ServletOutputStream outputStream = response.getOutputStream(); BufferedImage image = kaptcha.createImage(code); ImageIO.write(image, "jpg", outputStream); outputStream.flush(); outputStream.close(); } ``` 这段代码会在 /captcha.jpg 路径下生成验证码图片,并将验证码存入 Session 中。 4. 验证验证码 在需要验证验证码的地方,可以使用如下代码: ```java String captcha = request.getParameter("captcha"); String sessionCaptcha = (String) request.getSession().getAttribute("captcha"); if (!captcha.equalsIgnoreCase(sessionCaptcha)) { // 验证码错误 } ``` 这段代码会从请求参数中获取验证码,然后和 Session 中的验证码进行比对,如果不一致则说明验证码错误。 以上就是使用 Kaptcha 制作验证码的步骤,希望对您有帮助!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值