Servlet 生成验证码方法实例代码



Servlet 生成验证码方法实例代码。

Servlet方法:

 

  1. public class ValidateCodeServlet extends BaseServlet {
  2.     private static final String CONTENT_TYPE        = ”image/jpeg”;
  3.     /**
  4.      * 数字图像认证系统 随机产生一个四位的数组,转换成图象输出 产生的数组保存在Session中,绑定名字“rand”
  5.      *
  6.      * @param super.getRequest()
  7.      * @param super.getResponse()
  8.      */
  9.     public void createImage(HttpServletRequest request,
  10.             HttpServletResponse response)
  11.     {
  12.         response.setContentType(CONTENT_TYPE);
  13.         response.setHeader(“Pragma”,”No-cache”); // 设置页面不缓存
  14.         response.setHeader(“Cache-Control”,”no-cache”);
  15.         response.setDateHeader(“Expires”,0);
  16.         try {
  17.             request.setCharacterEncoding(“GBK”);
  18.         } catch (UnsupportedEncodingException e) {
  19.             e.printStackTrace();
  20.         }
  21.         HttpSession session = request.getSession();
  22.         // 产生四位随机码,写入session
  23.         //String chose = ”0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”;
  24.         //去掉容易混淆的字母:0,1,o,I,l,O
  25.         String chose = ”23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ”;
  26.         char display[] = { ’0′, ’ ’, ’0′, ’ ’, ’0′, ’ ’, ’0′ }, ran[] = { ’0′, ’0′, ’0′, ’0′ }, temp;
  27.         Random rand = new Random();
  28.         for (int i = 0; i < 4; i++)
  29.         {
  30.             temp = chose.charAt(rand.nextInt(chose.length()));
  31.             display[i * 2] = temp;
  32.             ran[i] = temp;
  33.         }
  34.         String strRandom = String.valueOf(display); // 与String.valueOf(ran)是相同地
  35.         String sRand = request.getParameter(“rand”); // 通过传递参数来设置验证码在session里的名字
  36.         if (sRand == null)
  37.         {
  38.             sRand = ”rand”;
  39.         }
  40.         session.setAttribute(sRand,String.valueOf(ran));
  41.         // 生成图像,返回到页页上
  42.         int width = 70, height = 26;
  43.         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  44.         Graphics g = image.getGraphics();
  45.         // 以下填充背景颜色
  46.         g.setColor(Color.white);
  47.         g.setColor(getRandomColor(200,250));
  48.         // 设置边框
  49.         g.fillRect(0,0,width,height);
  50.         // 设置字体颜色、字体
  51.         g.setColor(Color.black);
  52.         g.drawRect(0,0,width - 1,height - 1); // 字要比图像边框小一点
  53.         // 将认证码写入图像
  54.         g.setColor(Color.black);
  55.         g.setFont(new Font(“Arial”, Font.PLAIN, 18));
  56.         g.drawString(strRandom,1,18);
  57.         // 图像生效
  58.         g.dispose();
  59.         // 输出图像
  60.         try
  61.         {
  62.             ImageIO.write(image,”JPEG”,response.getOutputStream());
  63.         }
  64.         catch (Exception ex)
  65.         {
  66.             ex.printStackTrace();
  67.         }
  68.     }
  69.     /**
  70.      * 生成随机颜色
  71.      *
  72.      * @param fc
  73.      *            前景色
  74.      * @param bc
  75.      *            背景色
  76.      *
  77.      * @return Color对象,此Color对象是RGB形式的。
  78.      */
  79.     public Color getRandomColor(int fc, int bc)
  80.     {
  81.         Random random = new Random();
  82.         if (fc > 255)
  83.         {
  84.             fc = 200;
  85.         }
  86.         if (bc > 255)
  87.         {
  88.             bc = 255;
  89.         }
  90.         int r = fc + random.nextInt(bc - fc);
  91.         int g = fc + random.nextInt(bc - fc);
  92.         int b = fc + random.nextInt(bc - fc);
  93.         return new Color(r, g, b);
  94.     }
  95. }

页面:

 

 

  1. <script type=”text/javascript”>
  2.             jQuery(function(){
  3.                 jQuery(‘#urMobile’).focus();
  4.                 //为验证码图片绑定单击事件
  5.                 jQuery(“#imagepic”).click(function(){
  6.                     this.src=”<%=path%>/ValidateCodeServlet.do?method=createImage×tamp=”+Math.random();
  7.                 });
  8.             });
  9.         </script>
  1. <tr>
  2.                                 <td align=”right” height=”40″>
  3.                                     验证码:
  4.                                 </td>
  5.                                 <td align=”left”>
  6.                                     <input type=”text” size=”7″ name=”code” id=”code”/>
  7.                                     <img src=”<%=path%>/ValidateCodeServlet.do?method=createImage” id=”imagepic”
  8.                                     width=”75″ height=”24″ maxlength=”4″ title=”点击图片,更换验证码”/>
  9.                                 </td>
  10.                             </tr>

效果图: