第一步引入依赖
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
第二步下载并配置redis数据库,了解redis一些基本知识
第三步控制层处理
读取验证码
@Autowired
private Producer captchaProducer;
@RequestMapping("/kaptcha")
public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws Exception {
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
response.setContentType("image/jpeg");
//生成验证码
String capText = captchaProducer.createText();
session.setAttribute("kaptcha", capText);
System.out.println(session.getAttribute("kaptcha"));
//将验证码存储到redis数据库中
redisTemplate.opsForValue().set("kaptchaKsy",capText,60, TimeUnit.SECONDS );
//向客户端写出
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
}
调用Producer 得到验证码,并且存储到redis数据库中,可以设置存储时间等一些参数。
验证验证码
//登录
@ApiOperation("用户登录")
@PostMapping("/login/{code}")
public R login(@PathVariable("code")String code, User user1,HttpSession session){
User user = userService.login(user1);
if(user==null){
R.error("用户不存在");
}
//比较验证码
String code2= (String) redisTemplate.opsForValue().get("kaptchaKsy");
System.out.println(code2);
boolean codeFlag=code.equalsIgnoreCase(code2);
if(!codeFlag){
return R.error("验证码错误");
}
if(user1!=null){
return R.ok().put("user",user);
}else {
return R.error("登陆失败!请检查用户名或密码");
}
}
调用redisTemplate进行读取验证码,进而验证
到此springboot验证码验证的教程已经完毕,感兴趣的朋友们可以点个赞加个关注,我们一块学习java