• springboot验证码实现


    1.首先是生成验证码

    2.将生产的验证码保存在缓存中,只保存1-2分钟

    缓存使用的是:ExpiringMap(一个轻量的Java缓存方式)

    1. <dependency>
    2. <groupId>net.jodahgroupId>
    3. <artifactId>expiringmapartifactId>
    4. <version>0.5.8version>
    5. dependency>

    验证码的工具类:

    1. import java.awt.Color;
    2. import java.awt.Font;
    3. import java.awt.Graphics2D;
    4. import java.awt.image.BufferedImage;
    5. import java.util.Random;
    6. /*对图片进行处理的类和方法*/
    7. public class VerifyCode {
    8. public static String drawRandomText(int width,int height, BufferedImage verifyImg) {
    9. Graphics2D graphics = (Graphics2D)verifyImg.getGraphics();
    10. graphics.setColor(Color.WHITE);//设置画笔颜色-验证码背景色
    11. graphics.fillRect(0, 0, width, height);//填充背景
    12. graphics.setFont(new Font("微软雅黑", Font.BOLD, 40));
    13. // //数字和大小写字母的组合
    14. // String baseNumLetter= "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
    15. //数字和小写字母的组合
    16. String baseNumLetter= "123456789abcdefghijklmnopqrstuvwxyz";
    17. // //纯数字组合
    18. // String baseNumLetter= "123456789";
    19. StringBuffer sBuffer = new StringBuffer();
    20. int x = 10; //旋转原点的 x 坐标
    21. String ch = "";
    22. Random random = new Random();
    23. for(int i = 0;i < 4;i++){
    24. graphics.setColor(getRandomColor());
    25. //设置字体旋转角度
    26. int degree = random.nextInt() % 20; //角度小于20度
    27. int dot = random.nextInt(baseNumLetter.length());
    28. ch = baseNumLetter.charAt(dot) + "";
    29. sBuffer.append(ch);
    30. //正向旋转
    31. graphics.rotate(degree * Math.PI / 180, x, 45);
    32. graphics.drawString(ch, x, 45);
    33. //反向旋转
    34. graphics.rotate(-degree * Math.PI / 180, x, 45);
    35. x += 48;
    36. }
    37. //画干扰线
    38. for (int i = 0; i <3; i++) {
    39. // 设置随机颜色
    40. graphics.setColor(getRandomColor());
    41. // 随机画线
    42. graphics.drawLine(random.nextInt(width), random.nextInt(height),
    43. random.nextInt(width), random.nextInt(height));
    44. }
    45. //添加噪点
    46. for(int i=0;i<20;i++){
    47. int x1 = random.nextInt(width);
    48. int y1 = random.nextInt(height);
    49. graphics.setColor(getRandomColor());
    50. graphics.fillRect(x1, y1, 2,2);
    51. }
    52. return sBuffer.toString();
    53. }
    54. /**
    55. * 随机取色
    56. */
    57. private static Color getRandomColor() {
    58. Random ran = new Random();
    59. Color color = new Color(ran.nextInt(256),
    60. ran.nextInt(256), ran.nextInt(256));
    61. return color;
    62. }
    63. }

    验证码接口:

    1. import com.sws.nlflow.portal.util.ExpiringMap;
    2. import com.sws.nlflow.portal.util.VerifyCode;
    3. import java.awt.image.BufferedImage;
    4. import java.io.IOException;
    5. import java.io.OutputStream;
    6. import java.util.List;
    7. import javax.imageio.ImageIO;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import lombok.extern.slf4j.Slf4j;
    11. import org.springframework.stereotype.Controller;
    12. import org.springframework.web.bind.annotation.RequestMapping;
    13. /**
    14. * 验证码处理接口
    15. */
    16. @Slf4j
    17. @Controller
    18. @RequestMapping("/api")
    19. public class VerifyCodeController {
    20. @RequestMapping("/getVerifyCode")
    21. public void getVerificationCode(HttpServletResponse response, HttpServletRequest request) {
    22. try {
    23. int width = 200;
    24. int height = 69;
    25. BufferedImage verifyImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    26. //生成对应宽高的初始图片
    27. //功能是生成验证码字符并加上噪点,干扰线,返回值为验证码字符
    28. String randomText = VerifyCode.drawRandomText(width, height, verifyImg);
    29. // request.getSession().setAttribute("verifyCode", randomText);
    30. //获取ExpiringMap,将验证码保存在此处
    31. net.jodah.expiringmap.ExpiringMap VerifyCodemap = ExpiringMap.map;
    32. VerifyCodemap.put(randomText, randomText);
    33. response.setContentType("image/png");//必须设置响应内容类型为图片,否则前台不识别
    34. OutputStream os = response.getOutputStream(); //获取文件输出流
    35. ImageIO.write(verifyImg, "png", os);//输出图片流
    36. os.flush();
    37. os.close();//关闭流
    38. } catch (IOException e) {
    39. log.error(e.getMessage());
    40. e.printStackTrace();
    41. }
    42. }
    43. }

    缓存工具类:

    1. import java.io.Serializable;
    2. import java.util.concurrent.TimeUnit;
    3. import lombok.extern.slf4j.Slf4j;
    4. import net.jodah.expiringmap.ExpirationPolicy;
    5. /**
    6. * @author qushen
    7. * @create 2022/8/16 10:37
    8. */
    9. @Slf4j
    10. public class ExpiringMap implements Serializable {
    11. /**
    12. *
    13. * maxSize:map的最大长度,添加第1001个entry时,会导致第1个马上过期(即使没到过期时间)
    14. * expiration:过期时间和过期单位,设置过期时间,则永久有效.
    15. * expirationPolicy:过期策略的使用
    16. * CREATED: 在每次更新元素时,过期倒计时清零
    17. * ACCESSED: 在每次访问元素时,过期倒计时清零
    18. *
    19. * variableExpiration:允许更新过期时间值,如果不设置variableExpiration
    20. * 不允许更改过期时间,一旦执行更改过期时间的操作则会抛出UnsupportedOperationException异常
    21. * expirationListener:同步过期提醒
    22. * asyncExpirationListener:异步过期提醒
    23. * entryLoader:懒加载,调用get方法时若key不存在创建默认value
    24. *
    25. */
    26. public static net.jodah.expiringmap.ExpiringMap map = net.jodah.expiringmap.ExpiringMap.builder()
    27. //设置过期时间
    28. .expiration(120, TimeUnit.SECONDS)
    29. //设置过期协议
    30. .expirationPolicy(ExpirationPolicy.ACCESSED)
    31. .variableExpiration()
    32. .build();
    33. }

    登录时候的验证方法:

    1. //传入参数: VerifyCode
    2. net.jodah.expiringmap.ExpiringMap VerifyCodemap = ExpiringMap.map;
    3. if(!VerifyCodemap.containsKey(VerifyCode)){
    4. return new Response(Integer.valueOf(1), "验证码不正确!");
    5. }

  • 相关阅读:
    记一次任意文件下载到Getshell
    spark学习总结
    软件测试面试小技巧 | 如果你没收到offer我倒立洗头
    越细粒度的锁越好吗?产生死锁怎么办?
    工作手机定制服务
    vue可展开/收缩搜索条件且支持自适应功能
    Win10 使用ShareMouse与Mac共享鼠标键盘
    uniapp项目实践总结(二十)URLScheme 协议知识总结
    VBA_MF系列技术资料1-192
    chrome窗口
  • 原文地址:https://blog.csdn.net/weixin_38959210/article/details/126364764