`
zyc1006
  • 浏览: 132000 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

转struts2验证码

阅读更多

http://tmq.iteye.com/blog/286022

 

今天在struts2下实现了图片验证码的实例,基本思想如下:

1.实现产生图片验证码的action(其实产生图片的过程不应该在action里,这里为了方便全写在action里了)。

Action代码  收藏代码
  1. public class RandomAction extends ActionSupport{  
  2.     private ByteArrayInputStream inputStream;  
  3.     public String execute() throws Exception{  
  4. //       在内存中创建图象  
  5.         int width=85, height=20;  
  6.         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
  7. //       获取图形上下文  
  8.         Graphics g = image.getGraphics();  
  9. //      生成随机类  
  10.         Random random = new Random();  
  11. //       设定背景色  
  12.         g.setColor(getRandColor(200,250));  
  13.         g.fillRect(00, width, height);  
  14. //      设定字体  
  15.         g.setFont(new Font("Times New Roman",Font.PLAIN,18));  
  16. //       随机产生155条干扰线,使图象中的认证码不易被其它程序探测到  
  17.         g.setColor(getRandColor(160,200));  
  18.         for (int i=0;i<155;i++)  
  19.         {  
  20.          int x = random.nextInt(width);  
  21.          int y = random.nextInt(height);  
  22.                 int xl = random.nextInt(12);  
  23.                 int yl = random.nextInt(12);  
  24.          g.drawLine(x,y,x+xl,y+yl);  
  25.         }  
  26. //       取随机产生的认证码(6位数字)  
  27.         String sRand="";  
  28.         for (int i=0;i<6;i++){  
  29.             String rand=String.valueOf(random.nextInt(10));  
  30.             sRand+=rand;  
  31.             // 将认证码显示到图象中  
  32.             g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));  
  33. //      调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成  
  34.             g.drawString(rand,13*i+6,16);  
  35.         }  
  36. //       将认证码存入SESSION  
  37.         ActionContext.getContext().getSession().put("rand",sRand);  
  38. //       图象生效  
  39.         g.dispose();  
  40.         ByteArrayOutputStream output = new ByteArrayOutputStream();  
  41.         ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);  
  42.         ImageIO.write(image, "JPEG", imageOut);  
  43.         imageOut.close();  
  44.         ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());  
  45.         this.setInputStream(input);  
  46.         return SUCCESS;  
  47.     }  
  48.     /*  
  49.      * 给定范围获得随机颜色  
  50.      */  
  51.     private Color getRandColor(int fc,int bc){  
  52.         Random random = new Random();  
  53.         if(fc>255) fc=255;  
  54.         if(bc>255) bc=255;  
  55.         int r=fc+random.nextInt(bc-fc);  
  56.         int g=fc+random.nextInt(bc-fc);  
  57.         int b=fc+random.nextInt(bc-fc);  
  58.         return new Color(r,g,b);  
  59.    }  
  60.     public void setInputStream(ByteArrayInputStream inputStream) {  
  61.         this.inputStream = inputStream;  
  62.     }  
  63.     public ByteArrayInputStream getInputStream() {  
  64.         return inputStream;  
  65.     }  
  66.   
  67. }  

 2.配置action,将上述action返回的逻辑结果设置为文件流类型。

Struts.xml代码  收藏代码
  1. <action name="rand" class="test.RandomAction">  
  2.       <result type="stream">  
  3.                <param name="contentType">image/jpeg</param>  
  4.                <param name="inputName">inputStream</param>  
  5.         </result>  
  6.  </action>  

 3.写一个测试的html页面,使其请求上面的action,得到返回的图片结果。

显示图片验证码的html页代码  收藏代码
  1.  <script type="text/javascript">  
  2.     function changeValidateCode(obj) {  
  3.            //获取当前的时间作为参数,无具体意义  
  4.         var timenow = new Date().getTime();  
  5.            //每次请求需要一个不同的参数,否则可能会返回同样的验证码  
  6.         //这和浏览器的缓存机制有关系,也可以把页面设置为不缓存,这样就不用这个参数了。  
  7.         obj.src="rand.action?d="+timenow;  
  8.     }  
  9. </script>  
  10.   
  11. <img src="rand.action" onclick="changeValidateCode(this)"/>  

 

 现在可以看一下运行结果,点击图片可以改变验证码。如下图所示(当然,下面的图是不可以点的,是让你点自己运行后的程序)

 

上述的action只是为了方便才把所有东西都在action里实现了,实际上我在项目中使用的是一个辅助类RandomNumUtil,通过它的对象即可以取得图片,又可以取得图片上的字符串,此类定义如下: 

Java代码  收藏代码
  1. public class RandomNumUtil {  
  2.     private ByteArrayInputStream image;//图像  
  3.     private String str;//验证码  
  4.       
  5.     private RandomNumUtil(){  
  6.         init();//初始化属性  
  7.     }  
  8.     /* 
  9.      * 取得RandomNumUtil实例 
  10.      */  
  11.     public static RandomNumUtil Instance(){  
  12.         return new RandomNumUtil();  
  13.     }  
  14.     /* 
  15.      * 取得验证码图片 
  16.      */  
  17.     public ByteArrayInputStream getImage(){  
  18.         return this.image;  
  19.     }  
  20.     /* 
  21.      * 取得图片的验证码 
  22.      */  
  23.     public String getString(){  
  24.         return this.str;  
  25.     }  
  26.       
  27.     private void init() {  
  28.         //       在内存中创建图象  
  29.         int width=85, height=20;  
  30.         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
  31.         //       获取图形上下文  
  32.         Graphics g = image.getGraphics();  
  33.         //      生成随机类  
  34.         Random random = new Random();  
  35.         //       设定背景色  
  36.         g.setColor(getRandColor(200,250));  
  37.         g.fillRect(00, width, height);  
  38.         //      设定字体  
  39.         g.setFont(new Font("Times New Roman",Font.PLAIN,18));  
  40.         //       随机产生155条干扰线,使图象中的认证码不易被其它程序探测到  
  41.         g.setColor(getRandColor(160,200));  
  42.         for (int i=0;i<155;i++)  
  43.         {  
  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.         //       取随机产生的认证码(6位数字)  
  51.         String sRand="";  
  52.         for (int i=0;i<6;i++){  
  53.             String rand=String.valueOf(random.nextInt(10));  
  54.             sRand+=rand;  
  55.             // 将认证码显示到图象中  
  56.             g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));  
  57.             //      调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成  
  58.             g.drawString(rand,13*i+6,16);  
  59.             this.str=rand;/*   赋值验证码   */  
  60.         }  
  61.         //       图象生效  
  62.         g.dispose();  
  63.         ByteArrayInputStream input=null;  
  64.         ByteArrayOutputStream output = new ByteArrayOutputStream();  
  65.         try{  
  66.             ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);  
  67.             ImageIO.write(image, "JPEG", imageOut);  
  68.             imageOut.close();  
  69.             input = new ByteArrayInputStream(output.toByteArray());  
  70.         }catch(Exception e){  
  71.             System.out.println("验证码图片产生出现错误:"+e.toString());  
  72.         }  
  73.           
  74.         this.image=input;/*  赋值图像  */  
  75.     }  
  76.     /* 
  77.      * 给定范围获得随机颜色 
  78.      */  
  79.     private Color getRandColor(int fc,int bc){  
  80.         Random random = new Random();  
  81.         if(fc>255) fc=255;  
  82.         if(bc>255) bc=255;  
  83.         int r=fc+random.nextInt(bc-fc);  
  84.         int g=fc+random.nextInt(bc-fc);  
  85.         int b=fc+random.nextInt(bc-fc);  
  86.         return new Color(r,g,b);  
  87.    }  
  88.   
  89. }  


然后在action中如下使用此辅助类,action代码如下: 
Java代码  收藏代码
  1. public class RandomAction extends ActionSupport{  
  2.     private ByteArrayInputStream inputStream;  
  3.     public String execute() throws Exception{  
  4.         RandomNumUtil rdnu=RandomNumUtil.Instance();  
  5.         this.setInputStream(rdnu.getImage());//取得带有随机字符串的图片  
  6.         ActionContext.getContext().getSession().put("random", rdnu.getString());//取得随机字符串放入HttpSession  
  7.         return SUCCESS;  
  8.     }  
  9.     public void setInputStream(ByteArrayInputStream inputStream) {  
  10.         this.inputStream = inputStream;  
  11.     }  
  12.     public ByteArrayInputStream getInputStream() {  
  13.         return inputStream;  
  14.     }  


上述action代码不但有了图像,而且有了这个图像上的字符串对象,并且这个字符串对象保存在了session里。这样以后就可以从session中取出这个字符串来与客户输入的图片验证码来对照了。比如这位大哥所说的验证 验证码的action就可以这样来写: 
Java代码  收藏代码
  1. package test;  
  2.   
  3. import com.opensymphony.xwork2.ActionContext;  
  4. import com.opensymphony.xwork2.ActionSupport;  
  5.   
  6. public class CheckAction extends ActionSupport{  
  7.     private String str;//客户输入的图片验证码  
  8.       
  9.     public String execute(){  
  10.         String str2=(String)(ActionContext.getContext().getSession().get("random"));//取得session保存中的字符串  
  11.         //下面就是将session中保存验证码字符串与客户输入的验证码字符串对比了  
  12.         if(str2.equals(this.getStr())){  
  13.             return SUCCESS;  
  14.         }else{  
  15.             return LOGIN;  
  16.         }  
  17.     }  
  18.     public String getStr() {  
  19.         return str;  
  20.     }  
  21.   
  22.     public void setStr(String str) {  
  23.         this.str = str;  
  24.     }  
  25.   
  26. }  

这样总可以了吧老兄?基本思路就是先将产生的验证码字符串保存在session里,然后再从session中取出来与客户输入验证码的对比。至于怎么产数字与字母的组合图片验证码,老兄想想如何产生随机字母。。。。。。。?不多说了,自己动脑吧!

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics