JSP 验证码

 

  
  
           
  
  
  1. <%@ page language="java" import="java.util.*" pageEncoding="gbk"%>  
  2. <%@ page contentType="p_w_picpath/jpeg" 
  3.     import="java.awt.*,java.awt.p_w_picpath.*,java.util.*,javax.p_w_picpathio.*"%>  
  4.  
  5. <%!  
  6.     Color getRandColor(int cc, int bb)  
  7.  
  8.     {  
  9.  
  10.         Random random = new Random();  
  11.  
  12.         if (cc > 255)  
  13.             cc = 255;  
  14.  
  15.         if (bb > 255)  
  16.             bb = 255;  
  17.  
  18.         int r = cc + random.nextInt(bb - cc);  
  19.  
  20.         int g = cc + random.nextInt(bb - cc);  
  21.  
  22.         int b = cc + random.nextInt(bb - cc);  
  23.  
  24.         return new Color(r, g, b);  
  25.  
  26.     } //获取随机颜色  
  27. %>  
  28.  
  29. <%  
  30.     response.setHeader("Pragma""No-cache");  
  31.  
  32.     response.setHeader("Cache-Control""no-cache");  
  33.  
  34.     response.setDateHeader("Expires"0);  
  35.  
  36.     int width = 80//定义验证码图片的长度  
  37.  
  38.     int height = 30//定义验证码图片的宽度  
  39.  
  40.     BufferedImage p_w_picpath = new BufferedImage(width, height,  
  41.             BufferedImage.TYPE_INT_RGB);  
  42.  
  43.     Graphics g = p_w_picpath.getGraphics();  
  44.  
  45.     Random random = new Random();  
  46.  
  47.     g.setColor(getRandColor(200250));  
  48.  
  49.     g.fillRect(00, width, height);  
  50.  
  51.     g.setFont(new Font("Times New Roman", Font.PLAIN, 18));  
  52.  
  53.     //定义字体形式  
  54.  
  55.     g.setColor(getRandColor(160200));  
  56.  
  57.     for (int i = 0; i < 155; i++)  
  58.  
  59.     {  
  60.  
  61.         int i_x = random.nextInt(width);  
  62.  
  63.         int i_y = random.nextInt(height);  
  64.  
  65.         int i_xl = random.nextInt(12);  
  66.  
  67.         int i_yl = random.nextInt(12);  
  68.  
  69.         g.drawLine(i_x, i_y, i_x + i_xl, i_y + i_yl);  
  70.  
  71.     }  
  72.  
  73.     //用线条画背景  
  74.  
  75.     String s_Rand = "";  
  76.  
  77.     for (int i = 0; i < 4; i++)  
  78.  
  79.     {  
  80.  
  81.         String rand = String.valueOf(random.nextInt(10));  
  82.  
  83.         s_Rand += rand;  
  84.  
  85.         g.setColor(new Color(20 + random.nextInt(110), 20 + random  
  86.                 .nextInt(110), 20 + random.nextInt(110)));  
  87.  
  88.         g.drawString(rand, 13 * i + 616);  
  89.  
  90.     }  
  91.  
  92.     //产生4位随机码  
  93.  
  94.     session.setAttribute("rand", s_Rand);  
  95.  
  96.     //将验证码存入Session中  
  97.  
  98.     g.dispose();  
  99.  
  100.     ImageIO.write(p_w_picpath, "JPEG", response.getOutputStream());  
  101.  
  102.     //输出验证图片  
  103.  
  104.     out.clear();  
  105.  
  106.     out = pageContext.pushBody();  
  107. %>