JAVA代码生成验证码

深藏阁楼爱情的钟 2022-06-17 08:42 261阅读 0赞
  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. import javax.imageio.ImageIO;
  7. import javax.servlet.ServletException;
  8. import javax.servlet.ServletOutputStream;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import javax.servlet.http.HttpSession;
  12. import org.springframework.stereotype.Controller;
  13. import org.springframework.web.bind.annotation.RequestMapping;
  14. import org.springframework.web.bind.annotation.RequestMethod;
  15. /**
  16. * 生成验证码图片
  17. * @author crazy
  18. *
  19. */
  20. @Controller
  21. public class VerifyCodeController {
  22. // 验证码图片的宽度。
  23. private int width = 60;
  24. // 验证码图片的高度。
  25. private int height = 20;
  26. // 验证码字符个数
  27. private int codeCount = 4;
  28. private int x = 0;
  29. // 字体高度
  30. private int fontHeight;
  31. private int codeY;
  32. char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
  33. 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  34. 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
  35. /**
  36. * 初始化验证图片属性
  37. */
  38. public void initxuan() throws ServletException {
  39. // 从web.xml中获取初始信息
  40. // 宽度
  41. String strWidth ="120";
  42. // 高度
  43. String strHeight ="27";
  44. // 字符个数
  45. String strCodeCount = "4";
  46. // 将配置的信息转换成数值
  47. try {
  48. if (strWidth != null && strWidth.length() != 0) {
  49. width = Integer.parseInt(strWidth);
  50. }
  51. if (strHeight != null && strHeight.length() != 0) {
  52. height = Integer.parseInt(strHeight);
  53. }
  54. if (strCodeCount != null && strCodeCount.length() != 0) {
  55. codeCount = Integer.parseInt(strCodeCount);
  56. }
  57. } catch (NumberFormatException e) {
  58. }
  59. x = width / (codeCount + 1);
  60. fontHeight = height - 2;
  61. codeY = height - 4;
  62. }
  63. @RequestMapping(value="xuan/verifyCode",method=RequestMethod.GET)
  64. public void service(HttpServletRequest request, HttpServletResponse response)
  65. throws ServletException, java.io.IOException {
  66. initxuan();
  67. // 定义图像buffer
  68. BufferedImage buffImg = new BufferedImage(width, height,
  69. BufferedImage.TYPE_INT_RGB);
  70. Graphics2D g = buffImg.createGraphics();
  71. // 创建一个随机数生成器类
  72. Random random = new Random();
  73. // 将图像填充为白色
  74. g.setColor(Color.WHITE);
  75. g.fillRect(0, 0, width, height);
  76. // 创建字体,字体的大小应该根据图片的高度来定。
  77. Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
  78. // 设置字体。
  79. g.setFont(font);
  80. // 画边框。
  81. g.setColor(Color.BLACK);
  82. g.drawRect(0, 0, width - 1, height - 1);
  83. // 随机产生160条干扰线,使图象中的认证码不易被其它程序探测到。
  84. g.setColor(Color.BLACK);
  85. for (int i = 0; i < 10; i++) {
  86. int x = random.nextInt(width);
  87. int y = random.nextInt(height);
  88. int xl = random.nextInt(12);
  89. int yl = random.nextInt(12);
  90. g.drawLine(x, y, x + xl, y + yl);
  91. }
  92. // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
  93. StringBuffer randomCode = new StringBuffer();
  94. int red = 0, green = 0, blue = 0;
  95. // 随机产生codeCount数字的验证码。
  96. for (int i = 0; i < codeCount; i++) {
  97. // 得到随机产生的验证码数字。
  98. String strRand = String.valueOf(codeSequence[random.nextInt(36)]);
  99. // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
  100. red = random.nextInt(150);
  101. green = random.nextInt(150);
  102. blue = random.nextInt(150);
  103. // 用随机产生的颜色将验证码绘制到图像中。
  104. g.setColor(new Color(red, green, blue));
  105. g.drawString(strRand, (i + 1) * x, codeY);
  106. // 将产生的四个随机数组合在一起。
  107. randomCode.append(strRand);
  108. }
  109. // 将四位数字的验证码保存到Session中。
  110. HttpSession session = request.getSession();
  111. session.setAttribute("validateCode", randomCode.toString());
  112. // 禁止图像缓存。
  113. response.setHeader("Pragma", "no-cache");
  114. response.setHeader("Cache-Control", "no-cache");
  115. response.setDateHeader("Expires", 0);
  116. response.setContentType("image/jpg");
  117. // 将图像输出到Servlet输出流中。
  118. ServletOutputStream sos = response.getOutputStream();
  119. ImageIO.write(buffImg, "jpeg", sos);
  120. sos.close();
  121. }
  122. }
  123. <div class="row">
  124. <div class="col-sm-6">
  125. <input id="veryCode" name="veryCode" type="text" placeholder="验证码" required class="form-control" style="width:100%;"/>
  126. </div>
  127. <div class="col-sm-6 text-right">
  128. <img id="imgObj" alt="" src="${ctx }/xuan/verifyCode" οnclick="changeImg()"/>
  129. /div></div>
  130. function changeImg() {
  131. var src = $("#imgObj").attr("src");
  132. $("#imgObj").attr("src", chgUrl(src));
  133. }
  134. //时间戳
  135. //为了使每次生成图片不一致,即不让浏览器读缓存,所以需要加上时间戳
  136. function chgUrl(url) {
  137. var timestamp = (new Date()).valueOf();
  138. //url = url.substring(0, 17);
  139. url = url;
  140. if ((url.indexOf("&") >= 0)) {
  141. url = url + "×tamp=" + timestamp;
  142. } else {
  143. url = url + "?timestamp=" + timestamp;
  144. }
  145. return url;
  146. }
  147. 以上生成验证码的代码非本人所写,参考了某位大神的博客,现在找不到了,就在此声明.望博主原谅!

发表评论

表情:
评论列表 (有 0 条评论,261人围观)

还没有评论,来说两句吧...

相关阅读