开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 6 天,点击查看活动详情
本文介绍的是使用
easy-captcha这个Jar包,在后端生成二维码返回给前端使用。通过示例代码介绍各个步骤。
Maven的依赖包
将下述代码复制后,粘贴在Maven工程的pom.xml文件的<dependencies> </dependencies>中。
<!--easy-captch验证码-->
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>1.6.2</version>
</dependency>
<!--easy-captch验证码-->
编写API接口返回验证码图片
核心类是SpecCaptcha类,通过该类new出来的对象就是我们需要返回给前端的验证码对象。该SpecCaptcha类继承了Captcha类,并封装了大量即开即用的方法。
SpecCaptcha captcha = new SpecCaptcha(int width, int height, int len);
它的参数分别是定义验证码的:
- width:宽
- height:高
- len:验证码的长度(个数)
配置
上文
new出来的验证码对象可以进行一些设置,我们以对象captcha,进行如下常用的配置。
1. 设置验证码的类型
代码为我们提供如下的类型,因为它是static修饰的,所以设置的时候,我们直接通过Captcha.TYPE_DEFAULT选择类型即可。
public static final int TYPE_DEFAULT = 1; // 字母数字混合
public static final int TYPE_ONLY_NUMBER = 2; // 纯数字
public static final int TYPE_ONLY_CHAR = 3; // 纯字母
public static final int TYPE_ONLY_UPPER = 4; // 纯大写字母
public static final int TYPE_ONLY_LOWER = 5; // 纯小写字母
public static final int TYPE_NUM_AND_UPPER = 6; // 数字大写字母
代码默认就是TYPE_DEFAULT,字母数字混合方式的验证码。如果要修改的话,看下面示例代码,通过setCharType方法:
// 设置验证码类型为纯数字
captcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
2. 设置验证码的字体
同样,代码为我们提供了10种不同字体,用于设置验证码的字体,也是使用了static进行修饰,所以可以直接通过Captcha.FONT_1进行选择。
public static final int FONT_1 = 0;
public static final int FONT_2 = 1;
public static final int FONT_3 = 2;
public static final int FONT_4 = 3;
public static final int FONT_5 = 4;
public static final int FONT_6 = 5;
public static final int FONT_7 = 6;
public static final int FONT_8 = 7;
public static final int FONT_9 = 8;
public static final int FONT_10 = 9;
代码没有默认设置的字体,所以需要我们指定,通过setCharType方法即可:
// 设置验证码的字体
captcha.setCharType(Captcha.FONT_1);
通过输出流将二维码返回给前端
需要获取HttpServletResponse的getOutputStream,然后通过该输出流返回给前端。
// 输出图片流
captcha.out(httpServletResponse.getOutputStream());
但是这样还不够,需要设置返回的请求头。
// 1. 验证码一般是一次性的内容,无需进行缓存
httpServletResponse.setHeader("Cache-Control", "no-store");
// 2. 和1的作用差不多,也是表示验证码是一次性的内容,请求后就表示是一个过期资源
httpServletResponse.setDateHeader("Expires", 0);
// 3. 手动设置相应的内容类型是图片
httpServletResponse.setContentType("image/jpeg");
补充
所以,我们的API一般长这样:
public void getCapcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
}
- httpServletRequest:用于将生成的验证码,存入session中。
- httpServletResponse:用于设置输出的请求头。