Loading

谷歌开源kaptcha图形验证码开发

简介:谷歌开源kaptcha图形验证码开发

  • Kaptcha 框架介绍 谷歌开源的一个可高度配置的实用验证码生成工具
    • 验证码的字体/大小/颜色
    • 验证码内容的范围(数字,字母,中文汉字!)
    • 验证码图片的大小,边框,边框粗细,边框颜色
    • 验证码的干扰线
    • 验证码的样式(鱼眼样式、3D、普通模糊)

SpringBoot 开发kaptcha图形验证码接口

使用国内baomidou二次封装的springboot整合starter

github地址:https://gitee.com/baomidou/kaptcha-spring-boot-starter

1、引入 kaptcha-datasource-spring-boot-starter。

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>kaptcha-spring-boot-starter</artifactId>
  <version>${version}</version>
</dependency>

2、在Controller使用Kaptcha

@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {

  @Autowired
  private Kaptcha kaptcha;

  @GetMapping("/render")
  public void render() {
    kaptcha.render();
  }

  @PostMapping("/valid")
  public void validDefaultTime(@RequestParam String code) {
    //default timeout 900 seconds
    kaptcha.validate(code);
  }

  @PostMapping("/validTime")
  public void validCustomTime(@RequestParam String code) {
    kaptcha.validate(code, 60);
  }

}

3、发生错误会抛出异常,建议使用全局异常来处理。

KaptchaException  //super Exception

KaptchaIncorrectException

KaptchaNotFoundException

KaptchaTimeoutException

KaptchaRenderException //If something is wrong then Image.write when render.
import com.baomidou.kaptcha.exception.KaptchaException;
import com.baomidou.kaptcha.exception.KaptchaIncorrectException;
import com.baomidou.kaptcha.exception.KaptchaNotFoundException;
import com.baomidou.kaptcha.exception.KaptchaTimeoutException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

  @ExceptionHandler(value = KaptchaException.class)
  public String kaptchaExceptionHandler(KaptchaException kaptchaException) {
    if (kaptchaException instanceof KaptchaIncorrectException) {
      return "验证码不正确";
    } else if (kaptchaException instanceof KaptchaNotFoundException) {
      return "验证码未找到";
    } else if (kaptchaException instanceof KaptchaTimeoutException) {
      return "验证码过期";
    } else {
      return "验证码渲染失败";
    }
  }
}

4、自定义验证码参数,以下为默认配置。

kaptcha:
  height: 50
  width: 200
  content:
    length: 4
    source: abcdefghjklmnopqrstuvwxyz23456789
    space: 2
  font:
    color: black
    name: Arial
    size: 40
  background-color:
    from: lightGray
    to: white
  border:
    enabled: true
    color: black
    thickness: 1
posted @ 2021-02-06 14:04  PinGoo  阅读(874)  评论(0编辑  收藏  举报