欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > Spring验证码

Spring验证码

2025/4/17 6:41:16 来源:https://blog.csdn.net/LHY537200/article/details/140787123  浏览:    关键词:Spring验证码

 前言:使用Hutool

1.什么是Hutool?

2.代码复制到test类中

 

3.代码爆红,说明需要引入依赖

4.根据名取Maven仓库相关依赖

 

  

5.在pom.xml文件中进行配置 

6.引入成功

 

7. 运行程序

打开d盘,发现已经生成了验证码的图片,路径在上面提示有。 

  

使用其他验证码的方式相同,不赘述。

 


1.验证码项目

功能:后端实现验证码实现逻辑,前端负责返回的数据进行页面的提示。

实现:用户进行验证码输入,输入正确则跳转验证成功的页面,没输入或者输入不对,有弹窗提示,有60s的验证时间。

 

 

2.写生成验证码后端接口

 

1.先简单编写后端接口captcha(类CaptchaController)

2.验证是否成功 

 3.配置文件 

为什么要配置文件?

好进行封装,因为图片长宽高,session,date等都是可以设置的常量

session的key是拿到用户输入的验证码进行比较 

date指的是验证码的是时效。

这些都是可以设置为常量,你也可以在一个类中设置这些常量,但是如果有多个类要进行使用呢?

当然前期学习时我们是创建一个对象进行存储常量,但是我们这里是进行配置的学习啦。

这里把默认的application.properties修改成yml。

之所以修改单纯是为了练习。 

4. 创建一个CaptchaProperties对象

代码:

package com.example.demo.model;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Component
@ConfigurationProperties(prefix = "captcha")
@Data
public class CaptchaProperties {private Integer width;private Integer height;private Session session;@Datapublic static class Session{private String key;private String date;}}

为什么要创建一个对象?

比如拿现在有个常量要接受,你是要定义五个变量接收呢,还是使用一个对象接收?

 

代码: 

package com.example.demo.controller;  import cn.hutool.captcha.CaptchaUtil;  
import cn.hutool.captcha.LineCaptcha;  
import com.example.demo.model.CaptchaProperties;  
import jakarta.servlet.http.HttpServletRequest;  
import jakarta.servlet.http.HttpServletResponse;  
import jakarta.servlet.http.HttpSession;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RestController;  import java.io.IOException;  
import java.util.Date;  /**  * 验证码控制器,用于处理验证码的生成和验证  */  
@RequestMapping("/captcha")  
@RestController  
public class CaptchaController {  // 设置验证码在Session中的有效时间(毫秒)  private final static long SESSION_VALID_TIMEOUT = 60 * 1000;  // 注入CaptchaProperties配置类,用于获取验证码的配置信息  @Autowired  private CaptchaProperties captchaProperties;  /**  * 获取验证码图片  *   * @param session 用于存储验证码及其生成时间的HttpSession  * @param response 用于输出验证码图片的HttpServletResponse  */  @RequestMapping("/get")  public void getCaptcha(HttpSession session, HttpServletResponse response) {  // 根据CaptchaProperties中的配置生成一个线性验证码  LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());  // 设置响应的内容类型为图片  response.setContentType("image/jpg");  // 禁止浏览器缓存验证码图片  response.setHeader("Pragma", "No-cache");  // 将验证码图片写入到响应的输出流中  try {  lineCaptcha.write(response.getOutputStream());  // 将验证码文本存储在Session中,用于后续的验证  session.setAttribute(captchaProperties.getSession().getKey(), lineCaptcha.getCode());  // 可选:将验证码的生成时间也存储在Session中,以便进行过期检查  session.setAttribute(captchaProperties.getSession().getDate(), new Date());  // 关闭响应的输出流  response.getOutputStream().close();  } catch (IOException e) {  // 如果发生IO异常,则抛出运行时异常  throw new RuntimeException(e);  }  }  
}

3.写校验验证码check接口

代码:

   @RequestMapping("/check")public Boolean check(String inputCode, HttpSession session){//验证码生成的内容, 和用户输入的进行比较if (!StringUtils.hasLength(inputCode)){return false;}//从session获取信息String savedCode = (String) session.getAttribute(captchaProperties.getSession().getKey());Date saveDate = (Date) session.getAttribute(captchaProperties.getSession().getDate());if (inputCode.equalsIgnoreCase(savedCode)){//判断验证码是否过期if (saveDate!=null && System.currentTimeMillis()-saveDate.getTime() < session_valid_timeout){return true;}}return false;}}

 4.写前端代码index.html

代码: 

<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><title>验证码</title><style>#inputCaptcha {height: 30px;vertical-align: middle; }#verificationCodeImg{vertical-align: middle; }#checkCaptcha{height: 40px;width: 100px;}</style>
</head><body><h1>输入验证码</h1><div id="confirm"><input type="text" name="inputCaptcha" id="inputCaptcha"><img id="verificationCodeImg" src="/captcha/get" style="cursor: pointer;" title="看不清?换一张" /><input type="button" value="提交" id="checkCaptcha"></div><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script><script>$("#verificationCodeImg").click(function(){$(this).hide().attr('src', '/captcha/get?dt=' + new Date().getTime()).fadeIn();});$("#checkCaptcha").click(function () {$.ajax({url: "/captcha/check",type: "post",data: {inputCode: $("#inputCaptcha").val()},success:function(result){if(result){location.href = "success.html";}else{alert("验证码错误或者过期");}}});});</script>
</body></html>

5.写前端代码success.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>验证成功页</title>
</head>
<body><h1>验证成功</h1>
</body>
</html>

 

  6.展示:


 

 


 

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词