简单快速集成 Google Kaptcha验证码
QQ群:710314529
- 引入 kaptcha-datasource-spring-boot-starter。
<dependency>
<groupId>com.jun.plugin</groupId>
<artifactId>springboot_starter_kaptcha</artifactId>
<version>1.0</version>
</dependency>- 在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);
}
}- 发生错误会抛出异常,建议使用全局异常来处理。
KaptchaException //super Exception
KaptchaIncorrectException
KaptchaNotFoundException
KaptchaTimeoutException
KaptchaRenderException //If something is wrong then Image.write when render.import com.jun.plugin.kaptcha.exception.KaptchaException;
import com.jun.plugin.kaptcha.exception.KaptchaIncorrectException;
import com.jun.plugin.kaptcha.exception.KaptchaNotFoundException;
import com.jun.plugin.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 "验证码渲染失败";
}
}
}- 自定义验证码参数,以下为默认配置。
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