在java日常开发中,需要生成图形验证码,通常可以采用基于java本身封装的工具类。下面尝试一下EasyCaptcha插件,用于图形验证码生成,支持gif验证码,可用于基于的session的web项目和前后端分离的项目。
实例
1、pom依赖
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>1.6.2</version>
</dependency>
2、使用
@RequestMapping("/hello")
public void hello(HttpServletResponse response) throws IOException {
// png类型
SpecCaptcha captcha = new SpecCaptcha(130, 48);
// 获取验证码的字符
String text = captcha.text();
// 获取验证码的字符数组
char[] chars = captcha.textChar();
System.out.println("验证码:"+text);
System.out.println("验证码:"+chars);
// 输出验证码
captcha.out(response.getOutputStream());
}
@RequestMapping("/hello2")
public void hello2(HttpServletResponse response) throws IOException {
// 三个参数分别为宽、高、位数
GifCaptcha gifCaptcha = new GifCaptcha(100, 48, 4);
// 设置类型:字母数字混合
gifCaptcha.setCharType(Captcha.TYPE_DEFAULT);
//获取验证码
String text = gifCaptcha.text();
System.out.println("验证码为:"+text);
// 输出验证码
gifCaptcha.out(response.getOutputStream());
}
@RequestMapping("/hello3")
public void hello3(HttpServletResponse response) throws IOException {
// 中文类型
ChineseCaptcha captcha = new ChineseCaptcha(130, 48);
//获取验证码
String text = captcha.text();
System.out.println("验证码为:"+text);
// 输出验证码
captcha.out(response.getOutputStream());
}
@RequestMapping("/hello4")
public void hello4(HttpServletResponse response) throws IOException {
// 算术类型
ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
// 几位数运算,默认是两位
captcha.setLen(3);
// 获取运算的公式:4-9+1=?
captcha.getArithmeticString();
// 获取运算的结果:-4
String text = captcha.text();
System.out.println("计算结果为:"+text);
// 输出验证码
captcha.out(response.getOutputStream());
}
上面依次是png类型、gif类型、中文类型、算数类型
测试结果
感兴趣的可以尝试一下,是否可以简化开发。加油吧,少年。