本文主要是介绍easy-captcha生成验证码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
引入依赖
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><version>3.2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.whvcse/easy-captcha -->
<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 {@Autowiredprivate 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 {@Autowiredprivate StringRedisTemplate redisTemplate;@Overridepublic 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: localhostport: 6379database: 0
测试
这篇关于easy-captcha生成验证码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!