github链接:https://github.com/pig-mesh/easy-captcha
导入依赖
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>1.6.2</version>
</dependency>
CaptchaController
@Controller
public class CaptchaController {
@RequestMapping("/captcha")
public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 设置请求头为输出图片类型
response.setContentType("image/gif");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 三个参数分别为宽、高、位数
SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
// 设置字体
specCaptcha.setFont(new Font("Verdana", Font.PLAIN, 32)); // 有默认字体,可以不用设置
// 设置类型,纯数字、纯字母、字母数字混合
specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
// 验证码存入session
request.getSession().setAttribute("captcha", specCaptcha.text().toLowerCase());
// 输出图片流
specCaptcha.out(response.getOutputStream());
}
@PostMapping("/login")
public JsonResult login(String username,String password,String verCode){
// 获取session中的验证码
String sessionCode = request.getSession().getAttribute("captcha");
// 判断验证码
if (verCode==null || !sessionCode.equals(verCode.trim().toLowerCase())) {
return JsonResult.error("验证码不正确");
}
}
}
更多设置
验证码类型
public class Test {
public static void main(String[] args) {
// png类型
SpecCaptcha captcha = new SpecCaptcha(130, 48);
captcha.text(); // 获取验证码的字符
captcha.textChar(); // 获取验证码的字符数组
// gif类型
GifCaptcha captcha = new GifCaptcha(130, 48);
// 中文类型
ChineseCaptcha captcha = new ChineseCaptcha(130, 48);
// 中文gif类型
ChineseGifCaptcha captcha = new ChineseGifCaptcha(130, 48);
// 算术类型
ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
captcha.setLen(3); // 几位数运算,默认是两位
captcha.getArithmeticString(); // 获取运算的公式:3+2=?
captcha.text(); // 获取运算的结果:5
captcha.supportAlgorithmSign(2); // 可设置支持的算法:2 表示只生成带加减法的公式
captcha.setDifficulty(50); // 设置计算难度,参与计算的每一个整数的最大值
captcha.out(outputStream); // 输出验证码
//简单算术类型 SimpleArithmeticCaptcha,用法同ArithmeticCaptcha,只支持加减,计算结果为正整数
}
}
验证码字符类型
SpecCaptcha captcha = new SpecCaptcha(130, 48, 5);
captcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
// 只有SpecCaptcha和GifCaptcha设置才有效果。
字体设置
SpecCaptcha captcha = new SpecCaptcha(130, 48, 5);
// 设置内置字体
captcha.setFont(Captcha.FONT_1);
// 设置系统字体
captcha.setFont(new Font("楷体", Font.PLAIN, 28));