当前位置:   article > 正文

springboot验证码实现_springboot 内存缓存验证码

springboot 内存缓存验证码

代码链接:https://download.csdn.net/download/qq_37231511/14121983

程序结构:

1.创建springboot项目

2.工具类RandomValidateCodeUtil

  1. package com.xue.verificationcode.common.utils;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import javax.imageio.ImageIO;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import javax.servlet.http.HttpSession;
  8. import java.awt.*;
  9. import java.awt.image.BufferedImage;
  10. import java.util.Random;
  11. /**
  12. * @author cx
  13. * @Title: RandomValidateCodeUtil
  14. * @Package
  15. * @Description:
  16. * @date 2021/1/1210:43
  17. */
  18. public class RandomValidateCodeUtil {
  19. public static final String RANDOMCODEKEY = "RANDOMVALIDATECODEKEY";//放到session中的key
  20. private static final Logger logger = LoggerFactory.getLogger(RandomValidateCodeUtil.class);
  21. // private String randString = "0123456789";//随机产生只有数字的字符串 private String
  22. //private String randString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生只有字母的字符串
  23. private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生数字与字母组合的字符串
  24. private int width = 95;// 图片宽
  25. private int height = 25;// 图片高
  26. private int lineSize = 40;// 干扰线数量
  27. private int stringNum = 4;// 随机产生字符数量
  28. private Random random = new Random();
  29. /**
  30. * 获得字体
  31. */
  32. private Font getFont() {
  33. return new Font("Fixedsys", Font.CENTER_BASELINE, 18);
  34. }
  35. /**
  36. * 获得颜色
  37. */
  38. private Color getRandColor(int fc, int bc) {
  39. if (fc > 255)
  40. fc = 255;
  41. if (bc > 255)
  42. bc = 255;
  43. int r = fc + random.nextInt(bc - fc - 16);
  44. int g = fc + random.nextInt(bc - fc - 14);
  45. int b = fc + random.nextInt(bc - fc - 18);
  46. return new Color(r, g, b);
  47. }
  48. /**
  49. * 生成随机图片
  50. */
  51. public void getRandomCode(HttpServletRequest request, HttpServletResponse response) {
  52. HttpSession session = request.getSession();
  53. // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
  54. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
  55. // 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
  56. Graphics g = image.getGraphics();
  57. g.fillRect(0, 0, width, height);//图片大小
  58. g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));//字体大小
  59. g.setColor(getRandColor(110, 133));//字体颜色
  60. // 绘制干扰线
  61. for (int i = 0; i <= lineSize; i++) {
  62. drawLine(g);
  63. }
  64. // 绘制随机字符
  65. String randomString = "";
  66. for (int i = 1; i <= stringNum; i++) {
  67. randomString = drawString(g, randomString, i);
  68. }
  69. // logger.info(randomString);
  70. //将生成的随机字符串保存到session中
  71. session.removeAttribute(RANDOMCODEKEY);
  72. session.setAttribute(RANDOMCODEKEY, randomString);
  73. g.dispose();
  74. try {
  75. // 将内存中的图片通过流动形式输出到客户端
  76. ImageIO.write(image, "JPEG", response.getOutputStream());
  77. } catch (Exception e) {
  78. logger.error("将内存中的图片通过流动形式输出到客户端失败>>>> ", e);
  79. }
  80. }
  81. /**
  82. * 绘制字符串
  83. */
  84. private String drawString(Graphics g, String randomString, int i) {
  85. g.setFont(getFont());
  86. g.setColor(new Color(random.nextInt(101), random.nextInt(111), random
  87. .nextInt(121)));
  88. String rand = String.valueOf(getRandomString(random.nextInt(randString
  89. .length())));
  90. randomString += rand;
  91. g.translate(random.nextInt(3), random.nextInt(3));
  92. g.drawString(rand, 13 * i, 16);
  93. return randomString;
  94. }
  95. /**
  96. * 绘制干扰线
  97. */
  98. private void drawLine(Graphics g) {
  99. int x = random.nextInt(width);
  100. int y = random.nextInt(height);
  101. int xl = random.nextInt(13);
  102. int yl = random.nextInt(15);
  103. g.drawLine(x, y, x + xl, y + yl);
  104. }
  105. /**
  106. * 获取随机的字符
  107. */
  108. public String getRandomString(int num) {
  109. return String.valueOf(randString.charAt(num));
  110. }
  111. }

3.控制层VerifyCodeController

  1. package com.xue.verificationcode.controller;
  2. import com.xue.verificationcode.common.utils.RandomValidateCodeUtil;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.*;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. import javax.servlet.http.HttpSession;
  10. /**
  11. * @author cx
  12. * @Title: VerifyCodeController
  13. * @Package
  14. * @Description:
  15. * @date 2021/1/1117:17
  16. */
  17. @Controller
  18. @RequestMapping("/login")
  19. public class VerifyCodeController {
  20. private final static Logger logger = LoggerFactory.getLogger(VerifyCodeController.class);
  21. @RequestMapping("/index")
  22. public String getIndex(){
  23. return "index";
  24. }
  25. /**
  26. * 生成验证码
  27. */
  28. @RequestMapping(value = "/getVerify")
  29. @ResponseBody
  30. public void getVerify(HttpServletRequest request, HttpServletResponse response) {
  31. try {
  32. //设置相应类型,告诉浏览器输出的内容为图片
  33. response.setContentType("image/jpeg");
  34. //设置响应头信息,告诉浏览器不要缓存此内容
  35. response.setHeader("Pragma", "No-cache");
  36. response.setHeader("Cache-Control", "no-cache");
  37. response.setDateHeader("Expire", 0);
  38. RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
  39. randomValidateCode.getRandomCode(request, response);//输出验证码图片方法
  40. } catch (Exception e) {
  41. logger.error("获取验证码失败>>>> ", e);
  42. }
  43. }
  44. /**
  45. * 校验验证码
  46. */
  47. @RequestMapping(value = "/checkVerify", method = RequestMethod.POST, headers = "Accept=application/json")
  48. @ResponseBody
  49. public boolean checkVerify(@RequestParam String verifyInput, HttpSession session) {
  50. try {
  51. //从session中获取随机数
  52. String inputStr = verifyInput;
  53. String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
  54. if (random == null || "".equals(random) || !random.equalsIgnoreCase(inputStr)) {
  55. return false;
  56. } else {
  57. return true;
  58. }
  59. } catch (Exception e) {
  60. logger.error("验证码校验失败", e);
  61. return false;
  62. }
  63. }
  64. }

4.页面index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>登陆</title>
  6. </head>
  7. <style>
  8. #main_form {
  9. width: 300px;
  10. height: 200px;
  11. margin: 100px auto;
  12. background-color: #F0F0F0;
  13. border: 1px solid #c2c2c2;
  14. }
  15. #input_content {
  16. margin-top: 20px;
  17. text-align: center;
  18. border: 5px;
  19. }
  20. #verify_image, #submit_btn {
  21. text-align: center;
  22. margin: 20px auto;
  23. }
  24. </style>
  25. <body>
  26. <div id="main_form">
  27. <div id="input_content">
  28. <input autocomplete="off" autofocus id="verify_input" placeholder="请输入验证码" maxlength="4">
  29. </div>
  30. <div id="verify_image">
  31. <img id="imgVerify" src="getVerify" alt="更换验证码" height="36" width="170" onclick="getVerify(this);">
  32. </div>
  33. <div id="submit_btn">
  34. <input type="button" onclick="aVerify()" value="判断是否正确">
  35. </div>
  36. </div>
  37. </body>
  38. <!--<script type="text/javascript" src="./js/jquery.min.js"></script>-->
  39. <script type="text/javascript"src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
  40. <script>
  41. function getVerify() {
  42. $("#verify_input").val("");
  43. $("#imgVerify").attr("src", 'getVerify?' + Math.random());//jquery方式
  44. }
  45. function aVerify() {
  46. let value = $("#verify_input").val();
  47. if (value.length < 4) {
  48. alert("验证码不足4位 , 请重新输入!!");
  49. return 0;
  50. }
  51. $.ajax({
  52. async: false,
  53. type: 'post',
  54. url: 'checkVerify',
  55. dataType: "json",
  56. data: {
  57. verifyInput: value
  58. },
  59. success: function (result) {
  60. if (result) {
  61. if (confirm("验证成功, 再试一次 !")) {
  62. getVerify();
  63. } else {
  64. window.location.href = "https:www.baidu.com";
  65. }
  66. } else {
  67. alert("验证失败 , 点击确定重新验证");
  68. getVerify();
  69. }
  70. // window.location.reload();
  71. }
  72. });
  73. }
  74. </script>
  75. </html>

 

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

闽ICP备14008679号