1、验证码引用与生成

 
  
  1. 验证码:<html:text property="checkcode"></html:text> 
  2.     <img src="p_w_picpath.jsp"><br> 

p_w_picpath.jsp:

 
  
  1. <%@ page contentType="p_w_picpath/jpeg" import="java.awt.*,java.awt.p_w_picpath.*,java.util.*,javax.p_w_picpathio.*" %> 
  2. <%! 
  3. Color getRandColor(int fc,int bc){//给定范围获得随机颜色 
  4.         Random random = new Random(); 
  5.         if(fc>255) fc=255
  6.         if(bc>255) bc=255
  7.         int r=fc+random.nextInt(bc-fc); 
  8.         int g=fc+random.nextInt(bc-fc); 
  9.         int b=fc+random.nextInt(bc-fc); 
  10.         return new Color(r,g,b); 
  11.         } 
  12. %> 
  13. <% 
  14. //设置页面不缓存 
  15. response.setHeader("Pragma","No-cache"); 
  16. response.setHeader("Cache-Control","no-cache"); 
  17. response.setDateHeader("Expires"0); 
  18.  
  19. // 在内存中创建图象 
  20. int width=60, height=20
  21. BufferedImage p_w_picpath = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
  22.  
  23. // 获取图形上下文 
  24. Graphics g = p_w_picpath.getGraphics(); 
  25.  
  26. //生成随机类 
  27. Random random = new Random(); 
  28.  
  29. // 设定背景色 
  30. g.setColor(getRandColor(200,250)); 
  31. g.fillRect(00, width, height); 
  32.  
  33. //设定字体 
  34. g.setFont(new Font("Times New Roman",Font.PLAIN,18)); 
  35.  
  36. //画边框 
  37. //g.setColor(new Color()); 
  38. //g.drawRect(0,0,width-1,height-1); 
  39.  
  40.  
  41. // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到 
  42. g.setColor(getRandColor(160,200)); 
  43. for (int i=0;i<155;i++) 
  44.     int x = random.nextInt(width); 
  45.     int y = random.nextInt(height); 
  46.         int xl = random.nextInt(12); 
  47.         int yl = random.nextInt(12); 
  48.     g.drawLine(x,y,x+xl,y+yl); 
  49.  
  50. // 取随机产生的认证码(4位数字) 
  51. //String rand = request.getParameter("rand"); 
  52. //rand = rand.substring(0,rand.indexOf(".")); 
  53. String sRand=""
  54. for (int i=0;i<4;i++){ 
  55.     String rand=String.valueOf(random.nextInt(10)); 
  56.     sRand+=rand; 
  57.     // 将认证码显示到图象中 
  58.     g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成 
  59.     g.drawString(rand,13*i+6,16); 
  60.  
  61. // 将认证码存入SESSION 
  62. session.setAttribute("ccode",sRand); 
  63.  
  64.  
  65. // 图象生效 
  66. g.dispose(); 
  67.  
  68. // 输出图象到页面 
  69. ImageIO.write(p_w_picpath, "JPEG", response.getOutputStream()); 
  70.  
  71.  
  72. %>  

2、判断验证码是否正确:从session中取出验证码

 
  
  1. // 先判断验证码是否正确 
  2.         String ccode = (String) request.getSession().getAttribute("ccode"); 
  3.         String checkcode = userForm.getCheckcode(); 
  4.         if (!(checkcode.equals(ccode))) { 
  5.             ActionMessages errors = new ActionMessages(); 
  6.             errors.add("checkcode"new ActionMessage("checkcode.error")); 
  7.             super.saveErrors(request, errors); 
  8.             return mapping.getInputForward(); 
  9.         }