1,功能概述一般用于登录/注册界面中,主要功能是生成一个包含字母和数字的图形验证码。
2.除了springboot工程自带的依赖之外,主要要调用的依赖是:
<!-- hutu工具包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.18</version>//版本不固定
</dependency>
<!-- redis起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
3.验证码生成的方式有多种,这里使用的是hutoool工具包里面的方法。 利用工具包里面包,先定义验证码的大小和样式,之后就可以直接用getcode方法获取string类型的验证码了;
//定义验证码样式
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 10);
//得到验证码
String code = lineCaptcha.getCode();
4.将生成的string类型的验证码缓存redis之中 (1)先依赖注入:
@Autowired
private RedisTemplate redisTemplate;
(2)之后再缓存:
//redis存储验证码
redisTemplate.opsForValue().set("code",code);
5.向前端返回base64编码的图片,将验证码图片以Base64编码的形式嵌入到JSON响应中,以便前端可以直接将其用于HTML的<img>标签,而不需要额外的HTTP请求来获取图片,加强项目性能。
//返回Base64编码的图片JSON字符串
String imageBase64Data = lineCaptcha.getImageBase64Data();
//返回JSON格式ResponseResult对象
return Result.success(200,"success",imageBase64Data);
(QwQ)全部代码展示:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CaptchaController {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping("/cap")
public Result captcha(){
//定义验证码样式
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 10);
//得到验证码
String code = lineCaptcha.getCode();
//redis存储验证码
redisTemplate.opsForValue().set("code",code);
//返回Base64编码的图片JSON字符串
String imageBase64Data = lineCaptcha.getImageBase64Data();
//返回JSON格式ResponseResult对象
return Result.success(200,"success",imageBase64Data);
}
}