首頁 > 軟體

SpringBoot整合kaptcha實現圖片驗證碼功能

2022-07-28 14:03:07

栗子

登入是所有系統都繞不開的一道坎,很多系統會在使用者名稱和密碼下發放置一個圖形驗證碼,例如: 

這些圖形驗證碼看起來不僅很醜,而且模糊,但卻是保護系統的第一道屏障,它的作用是:設計的初衷其實就是為了防自動化,防止一些人利用自動工具惡意攻擊網站,比如批次註冊,撐爆你的資料庫。

實現這個功能並不複雜,但是為了不讓大家重複造輪子,這裡我給大家推薦一個現成的輪子: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內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com