java实现动态验证码生成(转)

本文转自http://www.iteye.com/topic/370847

1,生成动态验证码的Servlet。

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

 

2,用户登录验证的Servlet

Java代码   收藏代码
  1. package com.xcu.web;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.servlet.ServletException;  
  6. import javax.servlet.http.HttpServlet;  
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9.   
  10. import com.xcu.comm.CM;  
  11. import com.xcu.dao.UserDao;  
  12. import com.xcu.domain.Users;  
  13.   
  14.   
  15. public class LoginCheckServlet extends HttpServlet {  
  16.   
  17.     private static final long serialVersionUID = 4621074605453201722L;  
  18.       
  19.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  20.     throws ServletException, IOException {  
  21.         response.sendRedirect("noright.jsp");  
  22.     }  
  23.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  24.             throws ServletException, IOException {  
  25.   
  26.         request.setCharacterEncoding("utf-8");  
  27.           
  28.         String userName = request.getParameter("userName");  
  29.         String userPSD = request.getParameter("password");  
  30.         String validateCode = request.getParameter("validateCode");  
  31.           
  32.         Users user = new Users();  
  33.           
  34.         if(userName != null && userName.length()>0 ){  
  35.             user.setName(userName);  
  36.         }  
  37.         if(userPSD != null && userPSD.length()>0 ){  
  38.             user.setPsd(userPSD);  
  39.         }  
  40.   
  41.         String validateCodeInSession = (String) request.getSession()  
  42.                 .getAttribute(CM.VALIDATE_KEY);  
  43.   
  44.         request.getSession().removeAttribute(CM.VALIDATE_KEY);  
  45.           
  46.         if (validateCodeInSession == null || validateCode == null  
  47.                 || !validateCode.equalsIgnoreCase(validateCodeInSession)) {  
  48.             request.getSession().setAttribute(CM.ERR_MSG, "验证码错误");  
  49.             request.getSession().setAttribute("userName", userName);  
  50.             response.sendRedirect("login.jsp");  
  51.         } else {  
  52.             // 调用后台业务层的方法进行用户名和密码的校验!  
  53.             UserDao ud = new UserDao();  
  54.             if (ud.validateUser(user)) {  
  55.                 user = ud.find(user);  
  56.                 request.getSession().setAttribute("user", user);  
  57.                 response.sendRedirect("main.jsp");  
  58.             } else {  
  59.                 request.getSession().setAttribute(CM.ERR_MSG, "用户名或者密码错误");  
  60.                 request.getSession().setAttribute("userName", userName);  
  61.                 response.sendRedirect("login.jsp");  
  62.             }  
  63.         }  
  64.     }  
  65.   
  66. }  

 

 3,实用验证码的的JSP 页面。

Java代码   收藏代码
  1. <form method="post" action="login.do" name="form1">  
  2.                                                             <TABLE cellSpacing=0 cellPadding=0 width=318 border=0>  
  3.                                                                 <TBODY>  
  4.                                                                     <TR>  
  5.                                                                         <TD align=left>  
  6.                                                                             <font face="黑体"><span class="content_black_bold">用户名</span>   
  7.                                                                             <input type="text" id="userName" name="userName" value="${userName }" style="WIDTH: 200px" maxLength="20" />  
  8.                                                                             </font>  
  9.                                                                         </TD>  
  10.                                                                     </TR>  
  11.                                                                     <TR>  
  12.                                                                         <TD height=3>  
  13.                                                                             <font face="黑体"><img width="1" height="5" border="0" alt="" src="images/spacer.gif"></font>  
  14.                                                                         </TD>  
  15.                                                                     </TR>  
  16.                                                                     <TR>  
  17.                                                                         <TD align=left>  
  18.                                                                             <font face="黑体"><span class="content_black_bold">密&nbsp;&nbsp;&nbsp;&nbsp;码</span>  
  19.                                                                             <INPUT  style="WIDTH: 200px" type="password" maxLength=32 id="password" name="password" minlength="6" />  
  20.                                                                             </font>  
  21.                                                                         </TD>  
  22.                                                                     </TR>  
  23.                                                                     <TR>  
  24.                                                                         <TD height=3>  
  25.                                                                             <font face="黑体"><img width="1" height="5" border="0" alt="" src="images/spacer.gif"></font>  
  26.                                                                         </TD>  
  27.                                                                     </TR>  
  28.                                                                     <TR>  
  29.                                                                         <TD align=left valign="middle">  
  30.                                                                             <font face="黑体"><span class="content_black_bold">验证码</span>  
  31.                                                                             <INPUT  style="WIDTH: 80px" type="text" maxLength=32 id="validateCode" name="validateCode" minlength="6" />  
  32.                                                                             </font><img src="validatecode.jpg" name="validateCode"> <a href="javascript:newCode();">看不清?</a>  
  33.                                                                         </TD>  
  34.                                                                     </TR>  
  35.                                                                     <TR>  
  36.                                                                         <TD height=3>  
  37.                                                                             <font face="黑体"><img width="1" height="5" border="0" alt="" src="images/spacer.gif"></font>  
  38.                                                                         </TD>  
  39.                                                                     </TR>  
  40.                                                                     <TR>  
  41.                                                                         <TD height=3>  
  42.                                                                             <font face="黑体"><img width="1" height="5" border="0" alt="" src="images/spacer.gif"></font>  
  43.                                                                         </TD>  
  44.                                                                     </TR>  
  45.                                                                     <TR>  
  46.                                                                         <TD noWrap align=right>  
  47.                                                                             <font face="黑体"><span style="padding-right: 20px;"><input type="submit" value="登  录" οnclick="return check();"></span></font>  
  48.                                                                         </TD>  
  49.                                                                     </TR>  
  50.                                                                 </TBODY>  
  51.                                                             </TABLE>  
  52.                                                         </form>  

 

4,Web.xml中对生成验证码Servlet的配置映射。

Java代码   收藏代码
  1. <servlet>  
  2.  <servlet-name>ValidateCodeServlet</servlet-name>  
  3.  <servlet-class>com.xcu.web.ValidateCodeServlet</servlet-class>  
  4.  <init-param>  
  5.   <param-name>width</param-name>  
  6.   <param-value>60</param-value>  
  7.  </init-param>  
  8.  <init-param>  
  9.   <param-name>height</param-name>  
  10.   <param-value>20</param-value>  
  11.  </init-param>  
  12.  <init-param>  
  13.   <param-name>codeCount</param-name>  
  14.   <param-value>4</param-value>  
  15.  </init-param>  
  16. </servlet>  
  17.   
  18. <servlet-mapping>  
  19.  <servlet-name>ValidateCodeServlet</servlet-name>  
  20.  <url-pattern>/validatecode.jpg</url-pattern>  
  21. </servlet-mapping> 
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值