SpringBoot实现验证码案例

打印 上一主题 下一主题

主题 912|帖子 912|积分 2736

实现逻辑

1、后端功能:随机生成验证码图片,并把交给前端、接收用户输入,验证用户输入的验证码是否正确、
2、前端功能:显示验证码,提供输入框供用户输入他们看到的验证码,把用户输入的数据交给后端,接收后端返回的验证结果
前后端交互接口

后端必要完成的两个工作:1、生成验证码,2、校验验证码的正确性
接口定义:
1、生成验证码
请求url:/captcha/getCaptcha
相应:返回验证码的图片
2、校验验证码的正确性
请求url:/captcha/check
请求参数:用户输入的验证码captcha
相应:验证码正确返回true,错误返回false
前端代码

index.html
展示效果:
用户点击图片之后,可以更新验证码图片

代码如下:
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <head>
  4.         <meta charset="utf-8">
  5.         <title>验证码</title>
  6.         <style>
  7.             body {
  8.                 font-family: 'Arial', sans-serif;
  9.                 background-color: #f7f7f7;
  10.                 margin: 0;
  11.                 padding: 0;
  12.                 display: flex;
  13.                 justify-content: center;
  14.                 align-items: center;
  15.                 height: 100vh;
  16.             }
  17.             #container {
  18.                 text-align: center;
  19.                 background: white;
  20.                 padding: 50px;
  21.                 border-radius: 8px;
  22.                 box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  23.             }
  24.             h1 {
  25.                 color: #333;
  26.                 font-size: 2em;
  27.                 margin-bottom: 20px;
  28.             }
  29.             #inputCaptcha {
  30.                 height: 40px;
  31.                 margin-right: 10px;
  32.                 vertical-align: middle;
  33.                 border: 1px solid #ddd;
  34.                 border-radius: 4px;
  35.                 padding: 0 10px;
  36.             }
  37.             #verificationCodeImg {
  38.                 vertical-align: middle;
  39.                 border: 1px solid #ddd;
  40.                 cursor: pointer;
  41.                 transition: transform 0.2s;
  42.             }
  43.             #verificationCodeImg:hover {
  44.                 transform: scale(1.05);
  45.             }
  46.             #checkCaptcha {
  47.                 height: 40px;
  48.                 width: 120px;
  49.                 background-color: #5cb85c;
  50.                 color: white;
  51.                 border: none;
  52.                 border-radius: 4px;
  53.                 cursor: pointer;
  54.                 transition: background-color 0.2s;
  55.             }
  56.             #checkCaptcha:hover {
  57.                 background-color: #4cae4c;
  58.             }
  59.         </style>
  60.     </head>
  61.     <body>
  62.         <div id="container">
  63.             <h1>输入验证码</h1>
  64.             <div id="confirm">
  65.                 <input type="text" name="inputCaptcha" id="inputCaptcha">
  66.                 <img id="verificationCodeImg" src="http://127.0.0.1:8080/captcha/getCaptcha" style="cursor: pointer;"
  67.                      title="看不清?换一张"/>
  68.                 <input type="button" value="提交" id="checkCaptcha">
  69.             </div>
  70.         </div>
  71.         <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
  72.         <script>
  73.             $("#verificationCodeImg").click(function () {
  74.                 $(this).hide().attr('src', 'http://127.0.0.1:8080/captcha/getCaptcha?dt=' + new Date().getTime()).fadeIn();
  75.             });
  76.             $("#checkCaptcha").click(function () {
  77.                 $.ajax({
  78.                     type: "post",
  79.                     url: "captcha/check",
  80.                     data: {
  81.                         captcha: $("#inputCaptcha").val()
  82.                     },
  83.                     success: function (result) {
  84.                         if (result) {
  85.                             location.href = "success.html"
  86.                         } else {
  87.                             alert("验证码错误")
  88.                         }
  89.                     }
  90.                 });
  91.             });
  92.         </script>
  93.     </body>
  94. </html>
复制代码
success.html,当用户验证码输入正确时展示的内容
展示效果:

代码如下:
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <head>
  4.         <meta charset="UTF-8">
  5.         <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.         <title>验证成功页</title>
  7.         <style>
  8.             body {
  9.                 font-family: 'Arial', sans-serif;
  10.                 background-color: #f7f7f7;
  11.                 margin: 0;
  12.                 padding: 0;
  13.                 display: flex;
  14.                 justify-content: center;
  15.                 align-items: center;
  16.                 height: 100vh;
  17.             }
  18.             .container {
  19.                 text-align: center;
  20.                 background: white;
  21.                 padding: 50px;
  22.                 border-radius: 8px;
  23.                 box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  24.             }
  25.             h1 {
  26.                 color: green;
  27.                 font-size: 2.5em;
  28.                 margin: 0;
  29.             }
  30.             p {
  31.                 color: blue;
  32.                 font-size: 1.2em;
  33.                 margin-top: 20px;
  34.             }
  35.         </style>
  36.     </head>
  37.     <body>
  38.         <div class="container">
  39.             <h1>验证成功</h1>
  40.         </div>
  41.     </body>
  42. </html>
复制代码
后端代码

结构如下:

在pom.xml中添加依赖:

  1. <dependency>
  2.     <groupId>cn.hutool</groupId>
  3.     <artifactId>hutool-captcha</artifactId>
  4.     <version>5.8.26</version>
  5. </dependency>
复制代码
CaptchaController类:
  1. @RestController
  2. @RequestMapping("/captcha")
  3. public class CaptchaController {
  4.     //注入
  5.     @Autowired
  6.     private CaptchaProperties captchaProperties;
  7.     @Value("${captcha.session.key}")
  8.     private String key;
  9.     @Value("${captcha.session.datetime}")
  10.     private String datetime;
  11.     @RequestMapping("/getCaptcha")
  12.     public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
  13.         //定义图形验证码的长和宽
  14.         LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
  15.         String code = lineCaptcha.getCode();
  16.         //设置session,把验证码信息存储到session中
  17.         session.setAttribute(key, code);
  18.         session.setAttribute(datetime, new Date());
  19.         //验证码写入浏览器
  20.         lineCaptcha.write(response.getOutputStream());
  21.         //设置ContentType
  22.         response.setContentType("image/jpeg");
  23.         //设置编码
  24.         response.setCharacterEncoding("utf8");
  25.         //防止浏览器缓存验证码图片
  26.         response.setHeader("Pragma", "No-cache");
  27.     }
  28.     @RequestMapping("/check")
  29.     public boolean check(String captcha, HttpSession session) {
  30.         String code = (String) session.getAttribute(key);
  31.         if (!StringUtils.hasLength(captcha)) {
  32.             return false;
  33.         }
  34.         //从session中获取时间
  35.         Date date = (Date) session.getAttribute(datetime);
  36.         if (date == null || System.currentTimeMillis() - date.getTime() > 60 * 1000) {
  37.             //session为null,或者session过期(超过一分钟就算过期)
  38.             //System.currentTimeMillis() - date.getTime(): 当前时间-请求时间
  39.             return false;
  40.         }
  41.         //不区分大小写
  42.         return captcha.equalsIgnoreCase(code);
  43.     }
  44. }
复制代码
CaptchaProperties类:
  1. @ConfigurationProperties(prefix = "captcha")
  2. @Configuration
  3. @Data
  4. public class CaptchaProperties {
  5.     private Integer height;
  6.     private Integer width;
  7. }
复制代码
MySession类:
  1. @Data
  2. public class MySession {
  3.     private String key;
  4.     private String datetime;
  5. }
复制代码
配置文件 application.yml:
  1. captcha:
  2.   height: 50
  3.   width: 150
  4.   session:
  5.     key: CaptchaCode
  6.     datetime: CaptchaDate
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

慢吞云雾缓吐愁

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表