引入依赖
< dependency>
< groupId> org.springframework.boot</ groupId>
< artifactId> spring-boot-starter-data-redis</ artifactId>
< version> 3.2.4</ version>
</ dependency>
< dependency>
< groupId> com.github.whvcse</ groupId>
< artifactId> easy-captcha</ artifactId>
< version> 1.6.2</ version>
</ dependency>
编写相应前端实体vo
package com. orchids. springmybatisplus. model. entity ;
import io. swagger. v3. oas. annotations. media. Schema ;
import lombok. AllArgsConstructor ;
import lombok. Data ;
@Data
@Schema ( description = "图像验证码" )
@AllArgsConstructor
public class CaptchaVo {
@Schema ( description= "验证码图片信息" )
private String image;
@Schema ( description= "验证码key" )
private String key;
}
生成验证码
controller
@Controller
public class LoginController {
@Autowired
private LoginService loginService;
@Operation ( summary = "获取图形验证码" )
@GetMapping ( "login/captcha" )
public Result < CaptchaVo > getCaptcha ( ) {
CaptchaVo captcha = loginService. getCaptcha ( ) ;
return Result . ok ( captcha) ;
}
}
serviceimpl
@Service
public class LoginServiceImpl implements LoginService {
@Autowired
private StringRedisTemplate redisTemplate;
@Override
public CaptchaVo getCaptcha ( ) {
SpecCaptcha specCaptcha = new SpecCaptcha ( 100 , 40 , 4 ) ;
String code = specCaptcha. text ( ) . toLowerCase ( ) ;
String key = RedisConstant . ADMIN_LOGIN_PREFIX + UUID . randomUUID ( ) ;
String image = specCaptcha. toBase64 ( ) ;
redisTemplate. opsForValue ( ) . set ( key, code, 60 , TimeUnit . SECONDS ) ;
return new CaptchaVo ( image, key) ;
}
}
因为需要使用redis所以 需要在yml中配置redis
spring :
data :
redis :
host : localhost
port : 6379
database : 0
测试