验证码 这个功能 相信大家并不默认,也是项目中必须要涉及的内容,那么怎么去实现一个验证码功能呢。其实验证实现的方式很多。有session/cookie/数据库。我们这里主要使用Redis来实现验证码功能的存储。其实原理很简单。
(1)在后台生成验证码
( 2 ) 把生成的验证码存入redis
(3)返回到前台展示验证码
( 4 ) 输入验证码,完成验证功能
(1)生成验证码的功能,这里使用java.awt里面的Graphics 和 Image这些对象来绘制验证码
public void createImage(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
BufferedImage image = new BufferedImage(imageWidth, imageHigh, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
createBackground(g);
String captchaString = createCharacter(g);
String uuid = UUID.randomUUID().toString();
request.getSession().setAttribute("yzm_uuid",uuid);
// redis缓存验证码 将验证码缓存与Mengpeng 的文件夹下
redisService.setVal("mz:" + uuid, captchaString, 12000L);
g.dispose();
OutputStream out = response.getOutputStream();
ImageIO.write(image, "JPEG", out);
out.close();
}
(2)存入redis
redisService.setVal("mz:" + uuid, captchaString, 12000L);
同时设置过期时间
(3) 前台展示功能
<img src="/getImageCode" name="code" id="codeImageId" onclick="changeImage()" style="margin-left: 2px" height="38px" width="100px"/>
(4)验证功能也比较简单
public boolean verificationCode(HttpServletRequest request,String code) {
String yzm_uuid = (String)request.getSession().getAttribute("yzm_uuid");
String key ="mz:" + yzm_uuid;
String originCaptcha = redisService.getVal(key);
if (originCaptcha != null) {
if (code.equals(originCaptcha) == true) {
return true;
} else {
return false;
}
}
return false;
}
(5) 最终的效果图

完整代码 在码云可以获取 如果有疑问的 及时联系作者
https://gitee.com/soul_PreCoder/projects

使用Redis实现SSM在线图书管理系统验证码功能
本文介绍了如何在基于SSM的在线图书管理系统中利用Redis实现验证码功能。通过在后台生成验证码,将其存储到Redis,再展示给前端用户输入验证,详细阐述了验证码的生成、存储、展示和验证过程。
3300

被折叠的 条评论
为什么被折叠?



