Bootstrap

spring内置验证码kaptcha,baomidou使用详解

引入pom

		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>kaptcha-spring-boot-starter</artifactId>
			<version>1.1.0</version>
		</dependency>

application.yml 配置

kaptcha:
  height: 50
  width: 200
  content:
    length: 5
    source: abc12
    space: 2
  font:
    color: black
    name: Arial
    size: 40
  background-colo
    from: red
    to: white
  border:
    enabled: true
    color: black
    thickness: 1

height : 验证码框高
width :验证码框宽
content:内容
    length:验证码位数
    source:验证码区间 如:abcd1234,只会在这个区间产生
    space: 线的位置
font : 字体设置
    color: 字体颜色
    name: 字体设置
    size: 字体大小
background-colo : 颜色渐变设置
    from: 开头颜色
    to: 结尾颜色
boder :验证码框设置

如何使用

package com.test.execption.controller;

import com.baomidou.kaptcha.Kaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author admin
 * @date
 */
@RestController
@RequestMapping("/kcaptcha")
public class KcaptchaController {

	@Autowired
	private Kaptcha kaptcha;



	@GetMapping("/generator")
	public void generatorCode(HttpServletRequest request, HttpServletResponse response) {
		kaptcha.render();
	}

	@GetMapping("/verify")
	public String verify(String verifyCode, HttpServletRequest request) {

		Boolean aBoolean = kaptcha.validate(verifyCode, 10);
		if (aBoolean) {
			return "通过";
		}
		return "不通过";
	}
}

verify 方法校验说明
参数有两个,一个是校验码,一个是超时时间,主要为了方便扩展,超时时间可以有客户端来传入。
看源码
在这里插入图片描述
如果生成验证码的时间,超过了你传入的时间,那么会直接抛出异常KaptchaTimeoutException,看源码可以看到,这里没有返回true或者false,如果超时或者其他都是直接抛出异常,我们用的时候,可以自定义异常类,进行捕获异常进行处理。
如:

    @ExceptionHandler(KaptchaException.class)
    public String kcaptchaException(KaptchaException e){
        if (e instanceof KaptchaTimeoutException){
            return "超时";
        }else if (e instanceof KaptchaIncorrectException){
            return "不正确";
        }else if (e instanceof KaptchaNotFoundException){
            return "没找到";
        }else {
            return "反正错了";
        }
    }

截图展示

生成验证码
在这里插入图片描述

验证验证码
在这里插入图片描述

;