利用java自动生成验证码

迷南。 2022-08-21 12:40 223阅读 0赞
  1. 验证码生成有两种形式,一种是保存一定的验证码图片在数据库中然后把相应的验证码也保存起来。通过查询数据库来确定用户输入的验证码是否正确。但是这种方式有很大的问题,其一就是验证码图片数量过少很容易就会发生重复,其二是每次验证都要查询数据库影响性能。
  2. 所以我采用了第二种方式利用java画笔画出一个验证码图片出来。这样的好处是验证码基本每次都不一样,而且生成的验证码是放在session中的,验证起来也比较省时省力。推荐大家也使用这种方式。

下面就开始上代码介绍这种机制。

  1. import java.awt.Color;
  2. import java.awt.Font;
  3. import java.awt.Graphics2D;
  4. import java.awt.image.BufferedImage;
  5. import java.io.IOException;
  6. import java.util.Random;
  7. import javax.imageio.ImageIO;
  8. import javax.servlet.ServletException;
  9. import javax.servlet.ServletOutputStream;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import javax.servlet.http.HttpSession;
  13. import org.apache.struts2.ServletActionContext;
  14. public class CodeUtil {
  15. private HttpServletRequest request;
  16. private HttpServletResponse response;
  17. private int imgWidth = 0;//验证码图片的宽度
  18. private int imgHeight = 0;//验证码图片的高度
  19. private int codeCount = 0;//验证码的个数
  20. private int x = 0;
  21. private int fontHeight;
  22. private int codeY;
  23. private String fontStyle;
  24. private static final long serialVersionUID = 128554012633034503L;
  25. public CodeUtil(){
  26. init();
  27. try {
  28. response = ServletActionContext.getResponse();
  29. request = ServletActionContext.getRequest();
  30. response.setCharacterEncoding("UTF-8");
  31. request.setCharacterEncoding("UTF-8");
  32. response.setContentType("text/html;charset=UTF-8");
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. /**
  38. * 初始化配置参数
  39. */
  40. public void init(){
  41. // 宽度
  42. String strWidth = "60";
  43. // 高度
  44. String strHeight ="20";
  45. // 字符个数
  46. String strCodeCount = "4";
  47. fontStyle = "Times New Roman";
  48. // 将配置的信息转换成数值
  49. try {
  50. if (strWidth != null && strWidth.length() != 0) {
  51. imgWidth = Integer.parseInt(strWidth);
  52. }
  53. if (strHeight != null && strHeight.length() != 0) {
  54. imgHeight = Integer.parseInt(strHeight);
  55. }
  56. if (strCodeCount != null && strCodeCount.length() != 0) {
  57. codeCount = Integer.parseInt(strCodeCount);
  58. }
  59. } catch (NumberFormatException e) {
  60. e.printStackTrace();
  61. }
  62. x = imgWidth / (codeCount + 1);
  63. fontHeight = imgHeight - 2;
  64. codeY = imgHeight - 12;
  65. }
  66. /**
  67. *
  68. * @param request
  69. * @param response
  70. * @throws ServletException
  71. * @throws IOException
  72. */
  73. public void processRequest(HttpServletRequest request,
  74. HttpServletResponse response) throws ServletException, IOException {
  75. response.setContentType("image/jpg");
  76. response.setHeader("Pragma", "No-cache");
  77. response.setHeader("Cache-Control", "no-cache");
  78. response.setDateHeader("Expires", 0);
  79. HttpSession session = request.getSession();
  80. // 在内存中创建图象
  81. BufferedImage image = new BufferedImage(imgWidth, imgHeight,
  82. BufferedImage.TYPE_INT_RGB);
  83. // 获取图形上下文
  84. Graphics2D g = image.createGraphics();
  85. // 生成随机类
  86. Random random = new Random();
  87. // 设定背景色
  88. g.setColor(Color.WHITE);
  89. g.fillRect(0, 0, imgWidth, imgHeight);
  90. // 设定字体
  91. g.setFont(new Font(fontStyle, Font.PLAIN + Font.ITALIC, fontHeight));
  92. // 画边框
  93. g.setColor(new Color(55, 55, 12));
  94. g.drawRect(0, 0, imgWidth - 1, imgHeight - 1);
  95. // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
  96. g.setColor(getRandColor(160, 200));
  97. // for (int i = 0; i < 160; i++) {
  98. // int x = random.nextInt(imgWidth);
  99. // int y = random.nextInt(imgHeight);
  100. // int xl = random.nextInt(12);
  101. // int yl = random.nextInt(12);
  102. // g.drawLine(x, y, x + xl, y + yl);
  103. // }
  104. //
  105. // 取随机产生的认证码(4位数字)
  106. String sRand = "";
  107. int red = 0, green = 0, blue = 0;
  108. for (int i = 0; i < codeCount; i++) {
  109. red = random.nextInt(255);
  110. green = random.nextInt(255);
  111. blue = random.nextInt(255);
  112. int wordType = random.nextInt(3);
  113. char retWord = 0;
  114. switch (wordType) {
  115. case 0:
  116. retWord = this.getSingleNumberChar();
  117. break;
  118. case 1:
  119. retWord = this.getLowerOrUpperChar(0);
  120. break;
  121. case 2:
  122. retWord = this.getLowerOrUpperChar(1);
  123. break;
  124. }
  125. sRand += String.valueOf(retWord);
  126. g.setColor(new Color(red, green, blue));
  127. g.drawString(String.valueOf(retWord), (i) * x+5, codeY+7);//这个地方非常重要,关系到验证码是否居中显示。要根据大小进行调整。
  128. }
  129. // 将认证码存入SESSION
  130. sRand=sRand.toLowerCase();
  131. session.setAttribute("rand", sRand);
  132. // 图象生效
  133. g.dispose();
  134. ServletOutputStream responseOutputStream = response.getOutputStream();
  135. // 输出图象到页面
  136. ImageIO.write(image, "JPG", responseOutputStream);
  137. //
  138. // // 以下关闭输入流!
  139. responseOutputStream.flush();
  140. responseOutputStream.close();
  141. }
  142. Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
  143. Random random = new Random();
  144. if (fc > 255)
  145. fc = 255;
  146. if (bc > 255)
  147. bc = 255;
  148. int r = fc + random.nextInt(bc - fc);
  149. int g = fc + random.nextInt(bc - fc);
  150. int b = fc + random.nextInt(bc - fc);
  151. return new Color(r, g, b);
  152. }
  153. private char getSingleNumberChar() {
  154. Random random = new Random();
  155. int numberResult = random.nextInt(10);
  156. int ret = numberResult + 48;
  157. return (char) ret;
  158. }
  159. private char getLowerOrUpperChar(int upper) {
  160. Random random = new Random();
  161. int numberResult = random.nextInt(26);
  162. int ret = 0;
  163. if (upper == 0) {// 小写
  164. ret = numberResult + 97;
  165. } else if (upper == 1) {// 大写
  166. ret = numberResult + 65;
  167. }
  168. return (char) ret;
  169. }
  170. public void execute(){//程序执行的路口
  171. try {
  172. processRequest(request,response);
  173. } catch (Exception e) {
  174. e.printStackTrace();
  175. }
  176. }
  177. }

我这里用的是Struts2实现的,大家也可以用 Servlet实现。Demo下载地址点击打开链接

到这验证码的功能就实现了,这里的验证码生成的是图片的格式所以可以直接放在img的src中就可以访问到了。

如果有什么不清楚或者有啥疑问意见可以加我QQ/微信 208017534 ,欢迎一起交流一起进步。

  1. ![Center][]

发表评论

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

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

相关阅读

    相关 利用java自动生成验证

            验证码生成有两种形式,一种是保存一定的验证码图片在数据库中然后把相应的验证码也保存起来。通过查询数据库来确定用户输入的验证码是否正确。但是这种方式有很大的问题,