验证码作用
- 防止暴力破解
- 防止广告机注册等操作
1、导入Kaptcha依赖
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2、配置Config类
@Configuration
public class KaptchaConfig {
@Bean
public DefaultKaptcha defaultKaptcha() {
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
// 字体
properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_NAMES, "宋体,楷体,微软雅黑");
properties.setProperty(Constants.KAPTCHA_BORDER, "no");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
3、配置Controller
@RestController
@CrossOrigin //跨域
public class KaptchaController {
@Autowired
private DefaultKaptcha defaultKaptcha;
@Autowired
RedisTemplate redisTemplate;
@GetMapping("/createImageCode")
public void createImageCode(HttpServletRequest request,HttpServletResponse response) throws IOException {
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
// 生成文字验证码
String text = defaultKaptcha.createText();
// 生成图片验证码
BufferedImage image = defaultKaptcha.createImage(text);
// 这里我们使用redis缓存验证码的值,并设置过期时间为60秒
redisTemplate.opsForValue().set("imageCode",text,60, TimeUnit.SECONDS);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out);
out.flush();
out.close();
}
}
4、Vue前端表单代码
<el-image
:src="imageUrl"
style="width: 100px; height: 40px;float:right;cursor: pointer;"
fit="cover"
@click="uploadImage"
alt="验证码"
title="验证码"
></el-image>
// 获取验证码图片
uploadImage() {
// this.imageUrl = getVerifyImage().res.data
this.imageUrl = ''
this.$nextTick(()=>{
this.imageUrl = "http://192.168.7.50:8080/police/login/oauth/kaptcha"
})
},

刷新页面,验证码也会刷新,而且Redis也成功缓存了验证码的值

本篇博文到此结束,觉得不错的小伙伴可以***一键三连***哦!,感谢支持!!!










