Java实现随机验证码功能实例 (转)

现在许多系统的注册、登录或者发布信息模块都添加的随机码功能,就是为了避免自动注册程序或者自动发布程序的使用。

验证码实际上就 是随机选择一些字符以图片的形式展现在页面上,如果进行提交操作的同时需要将图片上的字符同时提交,如果提交的字符与服务器session保存的不同,则 认为提交信息无效。为了避免自动程序分析解析图片,通常会在图片上随机生成一些干扰线或者将字符进行扭曲,增加自动识别的难度。

在这里,我们使用servlet来实现随机验证码的实现。
java 代码
 
  1. package com.servlet;  
  2.   
  3. import java.awt.Color;  
  4. import java.awt.Font;  
  5. import java.awt.Graphics2D;  
  6. import java.awt.image.BufferedImage;  
  7. import java.util.Random;  
  8.   
  9. import javax.imageio.ImageIO;  
  10. import javax.servlet.ServletException;  
  11. import javax.servlet.ServletOutputStream;  
  12. import javax.servlet.http.HttpServlet;  
  13. import javax.servlet.http.HttpServletRequest;  
  14. import javax.servlet.http.HttpServletResponse;  
  15. import javax.servlet.http.HttpSession;  
  16.   
  17. /** 
  18. * 生成随机验证码 
  19. * @author bitiliu 
  20. * 
  21. */  
  22. public class ValidateCodeServlet extends HttpServlet  
  23. {  
  24.   
  25. private static final long serialVersionUID = 1L;  
  26.   
  27. //验证码图片的宽度。  
  28. private int width=60;  
  29. //验证码图片的高度。  
  30. private int height=20;  
  31. //验证码字符个数  
  32. private int codeCount=4;  
  33.   
  34.   
  35. private int x=0;  
  36. //字体高度  
  37. private int fontHeight;  
  38. private int codeY;  
  39.   
  40. char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',  
  41. 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',  
  42. 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };  
  43.   
  44. /** 
  45. * 初始化验证图片属性 
  46. */  
  47. public void init() throws ServletException  
  48. {  
  49. //从web.xml中获取初始信息  
  50. //宽度  
  51. String strWidth=this.getInitParameter("width");  
  52. //高度  
  53. String strHeight=this.getInitParameter("height");  
  54. //字符个数  
  55. String strCodeCount=this.getInitParameter("codeCount");  
  56.   
  57. //将配置的信息转换成数值  
  58. try  
  59. {  
  60. if(strWidth!=null && strWidth.length()!=0)  
  61. {  
  62. width=Integer.parseInt(strWidth);  
  63. }  
  64. if(strHeight!=null && strHeight.length()!=0)  
  65. {  
  66. height=Integer.parseInt(strHeight);  
  67. }  
  68. if(strCodeCount!=null && strCodeCount.length()!=0)  
  69. {  
  70. codeCount=Integer.parseInt(strCodeCount);  
  71. }  
  72. }  
  73. catch(NumberFormatException e)  
  74. {}  
  75.   
  76. x=width/(codeCount+1);  
  77. fontHeight=height-2;  
  78. codeY=height-4;  
  79.   
  80. }  
  81.   
  82. protected void service(HttpServletRequest req, HttpServletResponse resp)  
  83. throws ServletException, java.io.IOException {  
  84.   
  85. //定义图像buffer  
  86. BufferedImage buffImg = new BufferedImage(  
  87. width, height,BufferedImage.TYPE_INT_RGB);  
  88. Graphics2D g = buffImg.createGraphics();  
  89.   
  90. //创建一个随机数生成器类  
  91. Random random = new Random();  
  92.   
  93. //将图像填充为白色  
  94. g.setColor(Color.WHITE);  
  95. g.fillRect(00, width, height);  
  96.   
  97. //创建字体,字体的大小应该根据图片的高度来定。  
  98. Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);  
  99. //设置字体。  
  100. g.setFont(font);  
  101.   
  102. //画边框。  
  103. g.setColor(Color.BLACK);  
  104. g.drawRect(00, width - 1, height - 1);  
  105.   
  106. //随机产生160条干扰线,使图象中的认证码不易被其它程序探测到。  
  107. g.setColor(Color.BLACK);  
  108. for(int i = 0; i < 160; i++)  
  109. {  
  110. int x = random.nextInt(width);  
  111. int y = random.nextInt(height);  
  112. int xl = random.nextInt(12);  
  113. int yl = random.nextInt(12);  
  114. g.drawLine(x, y, x + xl, y + yl);  
  115. }  
  116.   
  117. //randomCode用于保存随机产生的验证码,以便用户登录后进行验证。  
  118. StringBuffer randomCode = new StringBuffer();  
  119. int red = 0, green = 0, blue = 0;  
  120.   
  121. //随机产生codeCount数字的验证码。  
  122. for (int i = 0; i < codeCount; i++) {  
  123. //得到随机产生的验证码数字。  
  124. String strRand = String.valueOf(codeSequence[random.nextInt(36)]);  
  125. //产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。  
  126. red = random.nextInt(255);  
  127. green = random.nextInt(255);  
  128. blue = random.nextInt(255);  
  129.   
  130. //用随机产生的颜色将验证码绘制到图像中。  
  131. g.setColor(new Color(red, green, blue));  
  132. g.drawString(strRand, (i + 1) * x, codeY);  
  133.   
  134. //将产生的四个随机数组合在一起。  
  135. randomCode.append(strRand);  
  136. }  
  137. // 将四位数字的验证码保存到Session中。  
  138. HttpSession session = req.getSession();  
  139. session.setAttribute("validateCode", randomCode.toString());  
  140.   
  141. // 禁止图像缓存。  
  142. resp.setHeader("Pragma""no-cache");  
  143. resp.setHeader("Cache-Control""no-cache");  
  144. resp.setDateHeader("Expires"0);  
  145.   
  146. resp.setContentType("image/jpeg");  
  147.   
  148. //将图像输出到Servlet输出流中。  
  149. ServletOutputStream sos = resp.getOutputStream();  
  150. ImageIO.write(buffImg, "jpeg", sos);  
  151. sos.close();  
  152. }  
  153.   
  154. }   

需要在web.xml中声明servlet
xml 代码
  1. <servlet>  
  2. <servlet-name>ValidateCodeServlet</servlet-name>  
  3. <servlet-class>com.servlet.ValidateCodeServlet</servlet-class>  
  4. <init-param>  
  5. <param-name>width</param-name>  
  6. <param-value>200</param-value>  
  7. </init-param>  
  8. <init-param>  
  9. <param-name>height</param-name>  
  10. <param-value>80</param-value>  
  11. </init-param>  
  12. <init-param>  
  13. <param-name>codeCount</param-name>  
  14. <param-value>5</param-value>  
  15. </init-param>  
  16. </servlet>  
  17.   
  18. <servlet-mapping>  
  19. <servlet-name>ValidateCodeServlet</servlet-name>  
  20. <url-pattern>/validateCodeServlet</url-pattern>  
  21. </servlet-mapping>   

用户提交后就可以将用户输入的验证码与session中保存的字符串进行比对,达到验证的效果。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值