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 "反正错了";
        }
    }

截图展示

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无奈的码农

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值