利用hutool工具类生成图形验证码

1.引入hutool依赖

    <dependency>
        <groupId>com.xiaoleilu</groupId>
        <artifactId>hutool-all</artifactId>
        <version>3.2.3</version>
    </dependency>

2.编写controller层代码
@RestController
public class CaptchaController {

//新建一个Springboot项目,勾选web就OK了,项目会自动集成logback,然后就能进行日志相关的操作了
private final Logger logger = LoggerFactory.getLogger(getClass());
// private final org.slf4j.Logger logger= LoggerFactory.getLogger(this.getClass());这种方式也行

@GetMapping("/getCaptcha")
public void getCaptcha(HttpServletResponse response, HttpSession session) {
    //生成验证码图片
    CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 25);

    //告诉浏览器输出内容为jpeg类型的图片
    response.setContentType("image/jpeg");
    //禁止浏览器缓存
    response.setHeader("Pragma", "No-cache");

// response.setHeader(“Cache-Control”, “no-cache”);
// response.setDateHeader(“Expire”, 0);
try {
ServletOutputStream outputStream = response.getOutputStream();
//图形验证码写出,可以写出到流,也可以写出到文件如circleCaptcha.write(“d:/circle25.jpeg”);
circleCaptcha.write(outputStream);
//从带有圆圈类型的图形验证码图片中获取它的字符串验证码(获取字符串验证码要在图形验证码写出wirte后面才行,不然得到的值为null)
String code = circleCaptcha.getCode();
//将字符串验证码保存到session中
session.setAttribute(“code”, code);
logger.info(“生成的验证码:{}”, code);
logger.info(“sessionId:{}”, session.getId());
//关闭流
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}

}

}

3.访问生成验证码接口得到图形验证码图片
在浏览器或者postman输入http://localhost:8080/getCaptcha访问
得到
在这里插入图片描述

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Hutool验证码工具类生成验证码,并将其展示在页面上,然后使用axios将用户输入的验证码发送给后端进行验证。 以下是一个示例代码: 前端部分: ```html <!-- 展示验证码 --> <img id="captchaImg" src="/captcha"> <!-- 输入框 --> <input type="text" id="captchaInput"> <!-- 验证按钮 --> <button onclick="verify()">验证</button> ``` ```javascript function verify() { const captcha = document.getElementById('captchaInput').value; axios.post('/verifyCaptcha', { captcha }).then(response => { if (response.data.success) { // 验证成功 } else { // 验证失败 } }); } ``` 后端部分: ```java // 生成验证码 String captcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 150).getCode(); // 将验证码存储到session中 request.getSession().setAttribute("captcha", captcha); // 验证验证码 String inputCaptcha = request.getParameter("captcha"); String sessionCaptcha = (String) request.getSession().getAttribute("captcha"); boolean success = inputCaptcha.equalsIgnoreCase(sessionCaptcha); ``` 在上面的示例代码中,前端展示了一个验证码图片,并提供了一个输入框和一个验证按钮。当用户点击验证按钮时,通过axios将用户输入的验证码发送到后端进行验证。后端使用Hutool验证码工具类生成验证码,并将其存储到session中。当用户输入验证码并点击验证按钮时,后端将用户输入的验证码与session中的验证码进行比较,判断验证码是否正确。最后,后端将验证结果返回给前端。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值