第一种使用ValidateCode实现验证码
ValidateCode是第三方依赖包,我们要先通过命令行引用一下
1.添加jar包到本地仓库
mvn install:install-file -DgroupId=cn.dsna.util.images -DartifactId=ValidateCode -Dversion=1.0 -Dfile=D:\ValidateCode.jar -Dpackaging=jar -DgeneratePom=true
根据自身情况修改对应的-DgroupId,-Dversion,和-Dfile。
2.更新本地仓库索引
以IDEA为例,操作如下:
File–>Settings–>搜索maven–>选择子项Repositores–>选中本地仓库–>update
3.在pom中使用jar
<dependency>
<groupId>cn.dsna.util.images</groupId>
<artifactId>ValidateCode</artifactId>
<version>1.0</version>
</dependency>
具体代码实现
public void getCode(HttpServletRequest request, HttpServletResponse response){
//参数列表:宽度,⾼度,字符数,⼲扰线数量
ValidateCode vs = new ValidateCode(120,40,5,100);
//获取文本
//String code = vs.getCode();
try {
//将文本放入redis中,一个公共的存储空间,存值的方式是key-value
redisTemplate.opsForValue().set("code",vs.getCode());
request.getSession().setMaxInactiveInterval(300);//永不过期为-1
vs.write(response.getOutputStream());
} catch (IOException e) {//有io流就可能有io流异常,就要加try catch语句
e.printStackTrace();
}
}
第二种使用base64实现验证码
private String doKaptcha(HttpServletRequest request) {
// 生成验证码
String text = kaptchaProducer.createText();
logger.info("kaptcha:" + text);
BufferedImage image = kaptchaProducer.createImage(text);
//将文本放入session中,一个公共的存储空间,存值的方式是key-value
HttpSession session = request.getSession();
session.setAttribute("kaptcha", text);
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpeg", outputStream);
String base64 = Base64.getEncoder().encodeToString(outputStream.toByteArray());
return "data:image/jpeg;base64," + base64.replaceAll("\r\n", "");
} catch (IOException e) {
return null;
}
}