JAVA生成验证码

原理:页面端通过定义img的src直接请求到服务器端,服务器端生成验证码图片,保存验证码值,并将图片通过流的方式返回到页面端。

生成验证码图片:通过Java绘制2D图片。下面代码:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.      * 随机生成验证码 
  3.      */  
  4.     public ModelAndView createCheckCode(HttpServletRequest request, HttpServletResponse response) throws IOException {  
  5.   
  6.         //加个线程休眠2秒是为了查看页面loading效果  
  7. //      Thread t = new Thread();  
  8. //      try {  
  9. //          t.sleep(2000);  
  10. //      } catch (InterruptedException e) {  
  11. //          e.printStackTrace();  
  12. //      }  
  13.           
  14.         //获取一个参数,是为区别html的img元素每次提交过来的src不同,达到更换验证码图片效果  
  15.         String nowCode = request.getParameter("nowCode");  
  16.         if(nowCode == null){  
  17.             return null;  
  18.         }  
  19.           
  20.         //验证码图片的宽度。  
  21.         int width = 60;  
  22.           
  23.         //验证码图片的高度。  
  24.         int height = 20;  
  25.           
  26.         //验证码字符个数  
  27.         int codeCount = 4;  
  28.   
  29.         //随机字符左右距离  
  30.         int marginLeft = 12;  
  31.           
  32.         //字体高度  
  33.         int fontHeight = 15;  
  34.           
  35.         //验证码字符与图片上边距的距离  
  36.         int marginTop = 15;  
  37.   
  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.         //初始化图像的Buffer对象  
  44.         BufferedImage bufferedImage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);  
  45.           
  46.         //创建图像画布  
  47.         Graphics2D g = bufferedImage.createGraphics();  
  48.   
  49.         //初始化一个随机数生成器类  
  50.         Random random = new Random();  
  51.   
  52.         //将图像填充为白色  
  53.         g.setColor(Color.WHITE);  
  54.           
  55.         //图像上实心白色矩形框  
  56.         g.fillRect(00, width, height);  
  57.   
  58.         //在图像上画一个空心的黑色边框  
  59.         g.setColor(Color.BLACK);  
  60.         g.drawRect(00, width - 1, height - 1);  
  61.   
  62.         //随机产生10条干扰线,使图象中的验证码不易被自动识别程序解析出来,干扰线多了字符看不清  
  63.         //g.setColor(Color.GRAY);  
  64.         g.setColor(new Color(127131142));   //灰色的干扰线容易看点  
  65.         for(int i = 0; i < 10; i++){  
  66.             int gx = random.nextInt(width); //在整个图像区域内产生干扰线  
  67.             int gy = random.nextInt(height);  
  68.             int gxl = random.nextInt(width);  
  69.             int gyl = random.nextInt(height);  
  70.             g.drawLine(gx, gy, gx + gxl, gy + gyl); //画线,两头的XY坐标  
  71.         }  
  72.   
  73.         //randomCode用于保存随机产生的验证码,以便用户登录后进行验证。  
  74.         StringBuffer randomCode = new StringBuffer();  
  75.         int red = 0;  
  76.         int green = 0;  
  77.         int blue = 0;  
  78.   
  79.         //创建字体,字体的大小应该根据图片的高度来定。  
  80.         Font fontCode = new Font("Microsoft YaHei", Font.BOLD, fontHeight);  
  81.         //设置字体。  
  82.         g.setFont(fontCode);  
  83.           
  84.         //随机产生基础字符内的验证码。  
  85.         for (int i = 0; i < codeCount; i++) {  
  86.             //在上面定义的基础字符内随机产生验证码  
  87.             String strRand = String.valueOf(codeSequence[random.nextInt(36)]);  
  88.               
  89.             //RGB随机产生值,这样输出的每位数字的颜色值都不同  
  90.             red = random.nextInt(255);  
  91.             green = random.nextInt(255);  
  92.             blue = random.nextInt(255);  
  93.       
  94.             //将随机产生的颜色值配置在验证码中  
  95.             g.setColor(new Color(red, green, blue));  
  96.               
  97.             //旋转文本  
  98.             //g.rotate(random.nextInt(2) * Math.PI / 180);  
  99.             //平移原点到图形环境的中心  ,这个方法的作用实际上就是将字符串移动到某一个位置   
  100.             //g.translate(1, 1);    
  101.                
  102.             g.drawString(strRand, (i + 1) * marginLeft - 5, marginTop);  
  103.               
  104.             //组合产生的验证码  
  105.             randomCode.append(strRand);   
  106.         }  
  107.           
  108.         //System.out.println(randomCode.toString());  
  109.           
  110.         //将产生的随机数存在session中,用作比对页面上输入的验证码值  
  111.         request.getSession().setAttribute("checkCodeValue", randomCode.toString());  
  112.         //禁止图像缓存。  
  113.         response.setHeader("Pragma""no-cache");  
  114.         response.setHeader("Cache-Control""no-cache");  
  115.         response.setDateHeader("Expires"0);  
  116.   
  117.         //设置图像返回客户端类型  
  118.         response.setContentType("image/jpeg");  
  119.   
  120.         //将图像以流的方式输出  
  121.         ServletOutputStream sos = response.getOutputStream();  
  122.         ImageIO.write(bufferedImage, "jpeg", sos);  
  123.         sos.close();  
  124.         return null;  
  125.     }  
下面一断是验证:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.      * 验证码校验 
  3.      */  
  4.     public ModelAndView checkCode(HttpServletRequest request, HttpServletResponse response) throws IOException {  
  5.         String nowCheckCodeValue = request.getParameter("checkCodeValue");  
  6.         String checkCodeValue = (String) request.getSession().getAttribute("checkCodeValue");  
  7.         //输入的验证码值和session中的进行比对,都转换成大写,因为基础字符中就是全大写,这样页面端可以忽略大小写  
  8.         if(nowCheckCodeValue.toUpperCase().equals(checkCodeValue)){  
  9.             response.setContentType("text/html;charset=UTF-8");  
  10.             response.getWriter().write("成功");  
  11.             return null;  
  12.         }else{  
  13.             response.setContentType("text/html;charset=UTF-8");  
  14.             response.getWriter().write("失败");  
  15.             return null;  
  16.         }  
  17.     }  
下面是jsp:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <%@ page language="java" pageEncoding="UTF-8"%>  
  2. <%String path = request.getContextPath();%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  7. <title>验证码测试</title>  
  8. <script type="text/javascript" src="<%=path%>/resources/easyui/jquery.min.js"></script>  
  9. <script type="text/javascript">  
  10. $(document).ready(function(){  
  11.   
  12.     $('#img-checkcode').bind('click', function () { /**为验证码图片绑定更换验证码事件**/  
  13.         $("#img-checkcode").attr("src",'loading.gif');  
  14.         var url = '/swmis/manage/init.do?method=createCheckCode';  
  15.         url += "&nowCode=" + (new Date()).getTime();  
  16.         this.src = url;  
  17.     });  
  18.       
  19.     setTimeout(function(){  /**初始化生成验证码,写个setTimeout是为了查看loading图片效果**/  
  20.         $("#img-checkcode").attr("src",'/swmis/manage/init.do?method=createCheckCode&nowCode=' + (new Date()).getTime());  
  21.     },2000);  
  22.       
  23. });  
  24.   
  25. function subOk(){   /**提交验证码比对**/  
  26.     var checkCodeValue = $("#txtCheckCode").val();  
  27.     $.ajax({  
  28.         type:'POST',  
  29.         async:true,  
  30.         url: '/swmis/manage/init.do?method=checkCode',  
  31.         data: {  
  32.             checkCodeValue : checkCodeValue  
  33.         },  
  34.         success:function(data){  
  35.             alert(data);  
  36.         }  
  37.     });  
  38. }  
  39. </script>  
  40. </head>  
  41. <body>  
  42.     <table style="margin: 26px auto;" cellpadding="2" cellspacing="2" width="600px" height="80px">  
  43.         <tr>  
  44.             <td width="100px" align="right">  
  45.                 <label>用户名:</label>  
  46.             </td>  
  47.             <td width="200px">  
  48.                 <input type="text" class="txt" id="txtUserName" name="txtUserName" value="admin" />  
  49.             </td>  
  50.             <td rowspan="2" align="left" width="200px">  
  51.                 <a href=javascript:login() class="btnLogin"></a>  
  52.             </td>  
  53.         </tr>  
  54.         <tr>  
  55.             <td width="100px" align="right">  
  56.                 <label>密码:</label>  
  57.             </td>  
  58.             <td width="200px">  
  59.                 <input type="password" class="txt" id="txtPassword" name="txtPassword" value="admin" />  
  60.             </td>  
  61.         </tr>  
  62.         <tr>  
  63.             <td width="100px" align="right">  
  64.                 <label>验证码:</label>  
  65.             </td>  
  66.             <td width="200px">  
  67.                 <input type="text" style="vertical-align: middle;" id="txtCheckCode" name="txtCheckCode" value="" />  
  68.                 <img style="vertical-align: middle;" id="img-checkcode" alt="猛击更换!" title="猛击更换!" src="loading.gif" style=" cursor:pointer" />  
  69.                 <!-- <img style="vertical-align: middle;" id="img-checkcode" alt="猛击更换!" title="猛击更换!" src="/swmis/manage/init.do?method=createCheckCode&nowCode=1" style=" cursor:pointer" /> -->  
  70.             </td>  
  71.         </tr>  
  72.         <tr>  
  73.             <td width="200px" colspan="2">  
  74.                 <input type="button" class="txt" id="btnSub" name="btnSub" value="提交" onclick="subOk()" />  
  75.             </td>  
  76.         </tr>  
  77.     </table>  
  78. </body>  
  79. </html>  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值