当前位置:   article > 正文

Java生成图形验证码

Java生成图形验证码

1、加依赖

  1. <dependency>
  2. <groupId>cn.hutool</groupId>
  3. <artifactId>hutool-all</artifactId>
  4. <version>5.8.16</version>
  5. </dependency>

2、写接口,这块不需要登录成功才能操作的,所以写controller就行了,不涉及服务

  1. package com.hmblogs.backend.controller;
  2. import cn.hutool.captcha.CaptchaUtil;
  3. import cn.hutool.captcha.LineCaptcha;
  4. import com.hmblogs.backend.config.CaptchaProperties;
  5. import com.hmblogs.backend.util.JedisUtil;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. import redis.clients.jedis.Jedis;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import javax.servlet.http.HttpSession;
  13. import java.io.IOException;
  14. @RestController
  15. @RequestMapping("/captcha")
  16. public class CaptchaController {
  17. @Autowired
  18. private CaptchaProperties captchaProp;
  19. @RequestMapping("/get")
  20. public void getCaptcha(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
  21. // 定义图形验证码的长和宽(配置默认值)
  22. LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProp.getWidth(), captchaProp.getHeight());
  23. // 细节问题,不影响程序
  24. // 设置返回类型
  25. response.setContentType("image/jpeg");
  26. // 静止缓存
  27. response.setHeader("Progma", "No-cache");
  28. try {
  29. // 图形验证码写出,可以写出到文件,也可以写出到流
  30. lineCaptcha.write(response.getOutputStream());
  31. // 这里是缓存图形验证码逻辑,也可以放库里,或者session里,但要用用户名区别,因为还没登录所以不要使用用户ID区别
  32. // 在相关功能(例如登录)的时候,要对应验证判断一下
  33. Jedis jedis = JedisUtil.getJedisConn();
  34. String username = request.getParameter("username");
  35. jedis.setex("imageToken:"+username,2*60, lineCaptcha.getCode());
  36. // 关流
  37. response.getOutputStream().close();
  38. } catch (IOException e) {
  39. throw new RuntimeException(e);
  40. }
  41. }
  42. }

3、对应的配置文件

  1. package com.hmblogs.backend.config;
  2. import lombok.Data;
  3. import org.springframework.boot.context.properties.ConfigurationProperties;
  4. import org.springframework.context.annotation.Configuration;
  5. @Data
  6. @Configuration
  7. @ConfigurationProperties(prefix = "captcha")
  8. public class CaptchaProperties {
  9. private Integer width;
  10. private Integer height;
  11. }

4、对应的配置文件的配置

  1. captcha:
  2. width: 200
  3. height: 100

5、开发页面,使用的是vue的ref来控制页面图形验证码区域显示,点击图片区域则会换一个图形验证码

6、验证

页面加载时,有调用该接口

查看redis的缓存,和页面看到的一致

点击图形区域,发现又调用了该接口

查看redis缓存

验证完毕。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/981803
推荐阅读
相关标签
  

闽ICP备14008679号