经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
spring boot实现验证码功能
来源:jb51  时间:2019/7/18 8:36:49  对本文有异议

本文实例为大家分享了spring boot实现验证码功能的具体代码,供大家参考,具体内容如下

流程是按照交互顺序。

1.controller层代码,获取验证码,以及生成验证码图片。

1.1获取html

  1. @RequestMapping(value="/authImage",method=RequestMethod.GET)
  2. public String authImage(){
  3. return "authImage";
  4. }

1.2 html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>验证码</title>
  5. </head>
  6. <body>
  7. <table>
  8. <tr>
  9. <td nowrap width="437"></td>
  10. <td>
  11. <img id="img" src="/image" />
  12. <a href='#' οnclick="javascript:changeImg()" style="color:white;"><label style="color:black;">看不清?</label></a>
  13. </td>
  14. </tr>
  15. </table>
  16. <!-- 触发JS刷新-->
  17. <script type="text/javascript">
  18. function changeImg(){
  19. var img = document.getElementById("img");
  20. img.src = "/image?date=" + new Date();
  21. }
  22. </script>
  23. </body>
  24. </html>

1.3.获取验证码图片

  1. @RequestMapping(value="/getImage",method=RequestMethod.GET)
  2. public void authImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
  3. response.setHeader("Pragma", "No-cache");
  4. response.setHeader("Cache-Control", "no-cache");
  5. response.setDateHeader("Expires", 0);
  6. response.setContentType("image/jpeg");
  7. // 生成随机字串
  8. String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
  9. // 存入会话session
  10. HttpSession session = request.getSession(true);
  11. // 删除以前的
  12. session.removeAttribute("verCode");
  13. session.removeAttribute("codeTime");
  14. session.setAttribute("verCode", verifyCode.toLowerCase());
  15. session.setAttribute("codeTime", LocalDateTime.now());
  16. // 生成图片
  17. int w = 100, h = 30;
  18. OutputStream out = response.getOutputStream();
  19. VerifyCodeUtils.outputImage(w, h, out, verifyCode);
  20. }

1.4 核对验证码 

  1. @RequestMapping(value="validImage",method=RequestMethod.GET)
  2. public String validImage(HttpServletRequest request,HttpSession session){
  3. String code = request.getParameter("code");
  4. Object verCode = session.getAttribute("verCode");
  5. if (null == verCode) {
  6. request.setAttribute("errmsg", "验证码已失效,请重新输入");
  7. return "验证码已失效,请重新输入";
  8. }
  9. String verCodeStr = verCode.toString();
  10. LocalDateTime localDateTime = (LocalDateTime)session.getAttribute("codeTime");
  11. long past = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
  12. long now = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
  13. if(verCodeStr == null || code == null || code.isEmpty() || !verCodeStr.equalsIgnoreCase(code)){
  14. request.setAttribute("errmsg", "验证码错误");
  15. return "验证码错误";
  16. } else if((now-past)/1000/60>5){
  17. request.setAttribute("errmsg", "验证码已过期,重新获取");
  18. return "验证码已过期,重新获取";
  19. } else {
  20. //验证成功,删除存储的验证码
  21. session.removeAttribute("verCode");
  22. return "200";
  23. }
  24. }

2、VerifyCodeUtils的工具类

  1. package com.example.springboot.demo.util.varcode;
  2. import java.awt.Color;
  3. import java.awt.Font;
  4. import java.awt.Graphics;
  5. import java.awt.Graphics2D;
  6. import java.awt.RenderingHints;
  7. import java.awt.geom.AffineTransform;
  8. import java.awt.image.BufferedImage;
  9. import java.io.File;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.OutputStream;
  13. import java.util.Arrays;
  14. import java.util.Random;
  15. import javax.imageio.ImageIO;
  16. public class VerifyCodeUtils{
  17. //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
  18. public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
  19. private static Random random = new Random();
  20. /**
  21. * 使用系统默认字符源生成验证码
  22. * @param verifySize 验证码长度
  23. * @return
  24. */
  25. public static String generateVerifyCode(int verifySize){
  26. return generateVerifyCode(verifySize, VERIFY_CODES);
  27. }
  28. /**
  29. * 使用指定源生成验证码
  30. * @param verifySize 验证码长度
  31. * @param sources 验证码字符源
  32. * @return
  33. */
  34. public static String generateVerifyCode(int verifySize, String sources){
  35. if(sources == null || sources.length() == 0){
  36. sources = VERIFY_CODES;
  37. }
  38. int codesLen = sources.length();
  39. Random rand = new Random(System.currentTimeMillis());
  40. StringBuilder verifyCode = new StringBuilder(verifySize);
  41. for(int i = 0; i < verifySize; i++){
  42. verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
  43. }
  44. return verifyCode.toString();
  45. }
  46. /**
  47. * 生成随机验证码文件,并返回验证码值
  48. * @param w
  49. * @param h
  50. * @param outputFile
  51. * @param verifySize
  52. * @return
  53. * @throws IOException
  54. */
  55. public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{
  56. String verifyCode = generateVerifyCode(verifySize);
  57. outputImage(w, h, outputFile, verifyCode);
  58. return verifyCode;
  59. }
  60. /**
  61. * 输出随机验证码图片流,并返回验证码值
  62. * @param w
  63. * @param h
  64. * @param os
  65. * @param verifySize
  66. * @return
  67. * @throws IOException
  68. */
  69. public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
  70. String verifyCode = generateVerifyCode(verifySize);
  71. outputImage(w, h, os, verifyCode);
  72. return verifyCode;
  73. }
  74. /**
  75. * 生成指定验证码图像文件
  76. * @param w
  77. * @param h
  78. * @param outputFile
  79. * @param code
  80. * @throws IOException
  81. */
  82. public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
  83. if(outputFile == null){
  84. return;
  85. }
  86. File dir = outputFile.getParentFile();
  87. if(!dir.exists()){
  88. dir.mkdirs();
  89. }
  90. try{
  91. outputFile.createNewFile();
  92. FileOutputStream fos = new FileOutputStream(outputFile);
  93. outputImage(w, h, fos, code);
  94. fos.close();
  95. } catch(IOException e){
  96. throw e;
  97. }
  98. }
  99. /**
  100. * 输出指定验证码图片流
  101. * @param w
  102. * @param h
  103. * @param os
  104. * @param code
  105. * @throws IOException
  106. */
  107. public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
  108. int verifySize = code.length();
  109. BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  110. Random rand = new Random();
  111. Graphics2D g2 = image.createGraphics();
  112. g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
  113. Color[] colors = new Color[5];
  114. Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
  115. Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
  116. Color.PINK, Color.YELLOW };
  117. float[] fractions = new float[colors.length];
  118. for(int i = 0; i < colors.length; i++){
  119. colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
  120. fractions[i] = rand.nextFloat();
  121. }
  122. Arrays.sort(fractions);
  123. g2.setColor(Color.GRAY);// 设置边框色
  124. g2.fillRect(0, 0, w, h);
  125. Color c = getRandColor(200, 250);
  126. g2.setColor(c);// 设置背景色
  127. g2.fillRect(0, 2, w, h-4);
  128. //绘制干扰线
  129. Random random = new Random();
  130. g2.setColor(getRandColor(160, 200));// 设置线条的颜色
  131. for (int i = 0; i < 20; i++) {
  132. int x = random.nextInt(w - 1);
  133. int y = random.nextInt(h - 1);
  134. int xl = random.nextInt(6) + 1;
  135. int yl = random.nextInt(12) + 1;
  136. g2.drawLine(x, y, x + xl + 40, y + yl + 20);
  137. }
  138. // 添加噪点
  139. float yawpRate = 0.05f;// 噪声率
  140. int area = (int) (yawpRate * w * h);
  141. for (int i = 0; i < area; i++) {
  142. int x = random.nextInt(w);
  143. int y = random.nextInt(h);
  144. int rgb = getRandomIntColor();
  145. image.setRGB(x, y, rgb);
  146. }
  147. shear(g2, w, h, c);// 使图片扭曲
  148. g2.setColor(getRandColor(100, 160));
  149. int fontSize = h-4;
  150. Font font = new Font("Algerian", Font.ITALIC, fontSize);
  151. g2.setFont(font);
  152. char[] chars = code.toCharArray();
  153. for(int i = 0; i < verifySize; i++){
  154. AffineTransform affine = new AffineTransform();
  155. affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
  156. g2.setTransform(affine);
  157. g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
  158. }
  159. g2.dispose();
  160. ImageIO.write(image, "jpg", os);
  161. }
  162. private static Color getRandColor(int fc, int bc) {
  163. if (fc > 255)
  164. fc = 255;
  165. if (bc > 255)
  166. bc = 255;
  167. int r = fc + random.nextInt(bc - fc);
  168. int g = fc + random.nextInt(bc - fc);
  169. int b = fc + random.nextInt(bc - fc);
  170. return new Color(r, g, b);
  171. }
  172. private static int getRandomIntColor() {
  173. int[] rgb = getRandomRgb();
  174. int color = 0;
  175. for (int c : rgb) {
  176. color = color << 8;
  177. color = color | c;
  178. }
  179. return color;
  180. }
  181. private static int[] getRandomRgb() {
  182. int[] rgb = new int[3];
  183. for (int i = 0; i < 3; i++) {
  184. rgb[i] = random.nextInt(255);
  185. }
  186. return rgb;
  187. }
  188. private static void shear(Graphics g, int w1, int h1, Color color) {
  189. shearX(g, w1, h1, color);
  190. shearY(g, w1, h1, color);
  191. }
  192. private static void shearX(Graphics g, int w1, int h1, Color color) {
  193. int period = random.nextInt(2);
  194. boolean borderGap = true;
  195. int frames = 1;
  196. int phase = random.nextInt(2);
  197. for (int i = 0; i < h1; i++) {
  198. double d = (double) (period >> 1)
  199. * Math.sin((double) i / (double) period
  200. + (6.2831853071795862D * (double) phase)
  201. / (double) frames);
  202. g.copyArea(0, i, w1, 1, (int) d, 0);
  203. if (borderGap) {
  204. g.setColor(color);
  205. g.drawLine((int) d, i, 0, i);
  206. g.drawLine((int) d + w1, i, w1, i);
  207. }
  208. }
  209. }
  210. private static void shearY(Graphics g, int w1, int h1, Color color) {
  211. int period = random.nextInt(40) + 10; // 50;
  212. boolean borderGap = true;
  213. int frames = 20;
  214. int phase = 7;
  215. for (int i = 0; i < w1; i++) {
  216. double d = (double) (period >> 1)
  217. * Math.sin((double) i / (double) period
  218. + (6.2831853071795862D * (double) phase)
  219. / (double) frames);
  220. g.copyArea(i, 0, 1, h1, 0, (int) d);
  221. if (borderGap) {
  222. g.setColor(color);
  223. g.drawLine(i, (int) d, i, 0);
  224. g.drawLine(i, (int) d + h1, i, h1);
  225. }
  226. }
  227. }
  228. }
  229. }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号