谷歌開源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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM