SpringBoot integrated verification code easy-captcha (including gif verification code)

1 Introduction

Java graphic verification code, supports gif, Chinese, arithmetic and other types, and can be used in Java Web, JavaSE and other projects.

2. Effect display

insert image description here

3. Import dependencies

		<dependency>
            <groupId>com.github.whvcse</groupId>
            <artifactId>easy-captcha</artifactId>
            <version>1.6.2</version>
        </dependency>

4. Code implementation

4.1 Implementation of gif verification code (realization of dynamic verification code)

4.1.1 Writing in the Controller of the SpringBoot project

Here R is the return entity class

package com.sky.api.sys.controller;

import com.sky.utils.R;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 尹稳健~
 * @version 1.0
 * @time 2022/9/21
 */
@RestController
@Api(tags = "系统管理-验证码")
public class CaptchaController {
    
    

    /**
     * 图形验证码接口
     * @return
     */
    @ApiOperation("图形验证码接口")
    @GetMapping("/captchaImage")
    public R<Map<String,Object>> captcha(){
    
    
        // 三个参数分别为宽、高、位数
        Captcha captcha = new GifCaptcha(130, 48, 4);
        // 设置字体,有默认字体,可以不用设置
        captcha.setFont(new Font("Verdana", Font.PLAIN, 32));
        // 设置类型,纯数字、纯字母、字母数字混合
        captcha.setCharType(Captcha.TYPE_DEFAULT);

        // 验证码存入redis
        // 将uuid作为redis的key
        String key = UUID.randomUUID().toString();

        String code = captcha.text().toLowerCase();

        Map<String, Object> map = new HashMap<>();

        map.put("key",key);
        map.put("code",captcha.toBase64());
        return R.ok(map);
    }
}

4.1.2 Front-end writing core code

Because the front end uses the vue index to just intercept part of the code.

<div class="login-code">
  <img :src="codeUrl" @click="getCode" class="login-code-img"/>
</div>



<script>

// 获取验证码图片
    getCode(){
      
      
      fetch.getCodeImg().then(res => {
      
      
        this.codeUrl = res.data.data.code;
        this.loginForm.uuid = res.data.data.key;
      })
    },
</script>

4.1.3 Result display

Because he is a gif so he can move
insert image description here
insert image description here

4.2 Implementation of other verification codes

4.2.1 Java code

/**
 * @author 尹稳健~
 * @version 1.0
 * @time 2022/9/21
 */
@RestController
@Api(tags = "系统管理-验证码")
public class CaptchaController {
    
    

    /**
     * 图形验证码接口
     * @return
     */
    @ApiOperation("图形验证码接口")
    @GetMapping("/captchaImage")
    public R<Map<String,Object>> captcha(){
    
    
        // png类型
        SpecCaptcha captcha = new SpecCaptcha(130, 48);
        captcha.text();  // 获取验证码的字符
        captcha.textChar();  // 获取验证码的字符数组
        
        // gif类型
        GifCaptcha captcha = new GifCaptcha(130, 48);
        
        // 中文类型
        ChineseCaptcha captcha = new ChineseCaptcha(130, 48);
        
        // 中文gif类型
        ChineseGifCaptcha captcha = new ChineseGifCaptcha(130, 48);
        
        // 算术类型
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
        captcha.setLen(3);  // 几位数运算,默认是两位
        captcha.getArithmeticString();  // 获取运算的公式:3+2=?
        captcha.text();  // 获取运算的结果:5
        captcha.supportAlgorithmSign(2); // 可设置支持的算法:2 表示只生成带加减法的公式
        captcha.setDifficulty(50); // 设置计算难度,参与计算的每一个整数的最大值
        captcha.out(outputStream);  // 输出验证码
        //简单算术类型 SimpleArithmeticCaptcha,用法同ArithmeticCaptcha,只支持加减,计算结果为正整数
    }
}

Note:
 The len of the arithmetic verification code represents the operation of several digits, while the len of other verification codes represents the number of digits of the verification code, and the text() of the arithmetic verification code represents the result of the formula. For the arithmetic verification code, you should put the formula The results are stored in the session, not the formula.

5. Verification code format setting

5.1 Six types of verification codes

type describe
TYPE_DEFAULT mix of numbers and letters
TYPE_ONLY_CHAR plain letters
TYPE_NUM_AND_UPPER Mixed numbers and capital letters
TYPE_ONLY_LOWER pure lowercase letters
TYPE_ONLY_NUMBER pure numbers
TYPE_ONLY_UPPER pure capital letters

5.2 How to use


// 三个参数分别为宽、高、位数
Captcha captcha = new GifCaptcha(130, 48, 4);
// 设置类型,纯数字、纯字母、字母数字混合
captcha.setCharType(Captcha.TYPE_DEFAULT);

5.3 Font Settings

insert image description here

There are two ways to use the default font.
Method 1:

Captcha captcha = new GifCaptcha(130, 48, 5);

// 设置内置字体
captcha.setFont(Captcha.FONT_1); 

// 设置系统字体
captcha.setFont(new Font("楷体", Font.PLAIN, 28)); 

Method 2:

// 三个参数分别为宽、高、位数
Captcha captcha = new GifCaptcha(130, 48, 4);
// 设置字体,有默认字体,可以不用设置
captcha.setFont(new Font("Verdana", Font.PLAIN, 32));

6. How to use it in actual combat

We can pass the verification code to the front end through the back end, so how should we pass it when we pass it?
If a verification code is passed in, what parameters should we pass in?
How to verify the verification code?
Where should the verification code be stored?
These are all questions to think about

Here I use a simple method, if there is a better method, please recommend it! ! !

train of thought

  • We put the code of the verification code, that is, its result into redis, and its key is a uuid. When we pass it from the back end to the front end, we pass a map collection, which contains uuid and picture content

  • At this time, someone may find out what is our backend passing over?
    insert image description here

  • data indicates the name of the agreement to obtain data;

  • image/png is the data type name;

  • base64 is the encoding method of the data. After the comma is the base64-encoded data of the image/png file.

  • Such a long thing is the verification code picture, no doubt

  • After the front end gets the data, it will bind the uuid to the form data entered by the user

  • Then the user submits the form, which will carry uuid, we first get the value of the verification code in redis through uuid

    • At this time, there are still two situations. The first one is that the verification code has expired. If you search it from redis through uuid, you can’t find it. We need to do exception handling
    • In the second case, the verification code entered by the user does not match the value we stored in redis, and we need to prompt him for an incorrect input
package com.sky.api.sys.controller;

import com.sky.utils.R;
import com.sky.utils.RedisCache;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 尹稳健~
 * @version 1.0
 * @time 2022/9/21
 */
@RestController
@Api(tags = "系统管理-验证码")
public class CaptchaController {
    
    

    @Autowired
    private RedisCache redisCache;

    /**
     * 图形验证码接口
     * @return
     */
    @ApiOperation("图形验证码接口")
    @GetMapping("/captchaImage")
    public R<Map<String,Object>> captcha(){
    
    
        // 三个参数分别为宽、高、位数
        Captcha captcha = new GifCaptcha(130, 48, 4);
        // 设置字体,有默认字体,可以不用设置
        captcha.setFont(new Font("Verdana", Font.PLAIN, 32));
        // 设置类型,纯数字、纯字母、字母数字混合
        captcha.setCharType(Captcha.TYPE_DEFAULT);

        // 验证码存入redis
        // 将uuid作为redis的key
        String key = UUID.randomUUID().toString();

        String code = captcha.text().toLowerCase();

        redisCache.setCacheObject(key,code,1, TimeUnit.MINUTES);

        Map<String, Object> map = new HashMap<>();

        map.put("key",key);
        map.put("code",captcha.toBase64());
        return R.ok(map);
    }
}

Intercept part of the code:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_46073538/article/details/127010750