Struts2 验证码图片实例

来源:互联网 发布:windows编程7 编辑:程序博客网 时间:2024/04/29 21:21

Struts2 验证码图片实例

本文分三个步骤介绍验证码图片生成以及与Struts2结合使用。 

Step 1.随机验证码

  一步一步来,要生成验证码图片,首先要有验证码,然后才能在画在图片上。为了能够灵活控制验证码,特别编写了SecurityCode类,它向外提供随机字符串。并且可以控制字符串的长度和难度。SecurityCode类中提供的验证码分三个难度,易(全数字)、中(数字+小写英文)、难(数字+大小写英文)。难度使用枚举SecurityCodeLevle表示,避免使用1、2、3这样没有明确意义的数字来区分。

  同时,还控制了能否出现重复的字符。为了能够方便使用,方法设计为static。

  SecurityCode类:

 

复制代码
 1 package com.dong.framework.tool; 2  3 import java.util.Arrays; 4  5 /** 6  * 工具类,生成随机验证码字符串 7  * @version 1.0 2012/08/21 8  * @author dongliyang 9  *10  */11 public class SecurityCode {12     13     /**14      * 验证码难度级别,Simple只包含数字,Medium包含数字和小写英文,Hard包含数字和大小写英文15      */16     public enum SecurityCodeLevel {Simple,Medium,Hard};17     18     /**19      * 产生默认验证码,4位中等难度20      * @return  String 验证码21      */22     public static String getSecurityCode(){23         return getSecurityCode(4,SecurityCodeLevel.Medium,false);24     }25     26     /**27      * 产生长度和难度任意的验证码28      * @param length  长度29      * @param level   难度级别30      * @param isCanRepeat  是否能够出现重复的字符,如果为true,则可能出现 5578这样包含两个5,如果为false,则不可能出现这种情况31      * @return  String 验证码32      */33     public static String getSecurityCode(int length,SecurityCodeLevel level,boolean isCanRepeat){34         35         //随机抽取len个字符36         int len=length;37         38         //字符集合(除去易混淆的数字0、数字1、字母l、字母o、字母O)39         char[] codes={'1','2','3','4','5','6','7','8','9',40                       'a','b','c','d','e','f','g','h','i',41                       'j','k','m','n','p','q','r','s','t',42                       'u','v','w','x','y','z','A','B','C',43                       'D','E','F','G','H','I','J','K','L',44                       'M','N','P','Q','R','S','T','U','V',45                       'W','X','Y','Z'};46         47         //根据不同的难度截取字符数组48         if(level==SecurityCodeLevel.Simple){49             codes=Arrays.copyOfRange(codes, 0,9);50         }else if(level==SecurityCodeLevel.Medium){51             codes=Arrays.copyOfRange(codes, 0,33);52         }53         54         //字符集合长度55         int n=codes.length;56         57         //抛出运行时异常58         if(len>n&&isCanRepeat==false){59             throw new RuntimeException(60                     String.format("调用SecurityCode.getSecurityCode(%1$s,%2$s,%3$s)出现异常," +61                                    "当isCanRepeat为%3$s时,传入参数%1$s不能大于%4$s",62                                    len,level,isCanRepeat,n));63         }64         65         //存放抽取出来的字符66         char[] result=new char[len];67         68         //判断能否出现重复的字符69         if(isCanRepeat){70             for(int i=0;i<result.length;i++){71                 //索引 0 and n-172                 int r=(int)(Math.random()*n);73             74                 //将result中的第i个元素设置为codes[r]存放的数值75                 result[i]=codes[r];76             }77         }else{78             for(int i=0;i<result.length;i++){79                 //索引 0 and n-180                 int r=(int)(Math.random()*n);81                 82                 //将result中的第i个元素设置为codes[r]存放的数值83                 result[i]=codes[r];84                 85                 //必须确保不会再次抽取到那个字符,因为所有抽取的字符必须不相同。86                 //因此,这里用数组中的最后一个字符改写codes[r],并将n减187                 codes[r]=codes[n-1];88                 n--;89             }90         }91         92         return String.valueOf(result);93     }94 }
复制代码

 

Step 2.图片

     第一步已经完成,有了上面SecurityCode类提供的验证码,就应该考虑怎么在图片上写字符串了。在Java中操作图片,需要使用BufferedImage类,它代表内存中的图片。写字符串,就需要从图片BufferedImage上得到绘图图面Graphics,然后在图面上drawString。

     为了使验证码有一定的干扰性,也绘制了一些噪点。调用Graphics类的drawRect绘制1*1大小的方块就可以了。

     特别说明一下,由于后面要与Strtus2结合使用,而在Struts2中向前台返回图片数据使用的是数据流的形式。所以提供了从图片向流的转换方法convertImageToStream。

     SecurityImage类:

 

复制代码
  1 package com.dong.framework.tool;  2   3 import java.awt.Color;  4 import java.awt.Font;  5 import java.awt.Graphics;  6 import java.awt.image.BufferedImage;  7 import java.io.ByteArrayInputStream;  8 import java.io.ByteArrayOutputStream;  9 import java.io.IOException; 10 import java.util.Random; 11 import com.sun.image.codec.jpeg.ImageFormatException; 12 import com.sun.image.codec.jpeg.JPEGCodec; 13 import com.sun.image.codec.jpeg.JPEGImageEncoder; 14  15 /** 16  * 工具类,生成验证码图片 17  * @version 1.0 2012/08/21 18  * @author dongliyang 19  * 20  */ 21 public class SecurityImage { 22      23     /** 24      * 生成验证码图片 25      * @param securityCode   验证码字符 26      * @return  BufferedImage  图片 27      */ 28     public static BufferedImage createImage(String securityCode){ 29          30         //验证码长度 31         int codeLength=securityCode.length(); 32         //字体大小 33         int fSize = 15; 34         int fWidth = fSize + 1; 35         //图片宽度 36         int width = codeLength * fWidth + 6 ; 37         //图片高度 38         int height = fSize * 2 + 1; 39          40         //图片 41         BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 42         Graphics g=image.createGraphics(); 43          44         //设置背景色 45         g.setColor(Color.WHITE); 46         //填充背景 47         g.fillRect(0, 0, width, height); 48          49         //设置边框颜色 50         g.setColor(Color.LIGHT_GRAY); 51         //边框字体样式 52         g.setFont(new Font("Arial", Font.BOLD, height - 2)); 53         //绘制边框 54         g.drawRect(0, 0, width - 1, height -1); 55          56          57         //绘制噪点 58         Random rand = new Random(); 59         //设置噪点颜色 60         g.setColor(Color.LIGHT_GRAY); 61         for(int i = 0;i < codeLength * 6;i++){ 62             int x = rand.nextInt(width); 63             int y = rand.nextInt(height); 64             //绘制1*1大小的矩形 65             g.drawRect(x, y, 1, 1); 66         } 67          68         //绘制验证码 69         int codeY = height - 10;   70         //设置字体颜色和样式 71         g.setColor(new Color(19,148,246)); 72         g.setFont(new Font("Georgia", Font.BOLD, fSize)); 73         for(int i = 0; i < codeLength;i++){ 74             g.drawString(String.valueOf(securityCode.charAt(i)), i * 16 + 5, codeY); 75         } 76         //关闭资源 77         g.dispose(); 78          79         return image; 80     } 81      82     /** 83      * 返回验证码图片的流格式 84      * @param securityCode  验证码 85      * @return ByteArrayInputStream 图片流 86      */ 87     public static ByteArrayInputStream getImageAsInputStream(String securityCode){ 88          89         BufferedImage image = createImage(securityCode); 90         return convertImageToStream(image); 91     } 92      93     /** 94      * 将BufferedImage转换成ByteArrayInputStream 95      * @param image  图片 96      * @return ByteArrayInputStream 流 97      */ 98     private static ByteArrayInputStream convertImageToStream(BufferedImage image){ 99         100         ByteArrayInputStream inputStream = null;101         ByteArrayOutputStream bos = new ByteArrayOutputStream();102         JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(bos);103         try {104             jpeg.encode(image);105             byte[] bts = bos.toByteArray();106             inputStream = new ByteArrayInputStream(bts);107         } catch (ImageFormatException e) {108             e.printStackTrace();109         } catch (IOException e) {110             e.printStackTrace();111         }112         return inputStream;113     }114 }
复制代码

 

Step 3.验证码与Struts 2结合

  1)Action

  有了上面两步操作作为铺垫,含有验证码的图片就不成问题了,下面就可以使用Struts2的Action向前台返回图片数据了。

      SecurityCodeImageAction类:

复制代码
 1 package com.dong.security.action; 2  3 import com.opensymphony.xwork2.ActionSupport; 4 import java.io.ByteArrayInputStream; 5 import java.util.Map; 6 import org.apache.struts2.interceptor.SessionAware; 7 import com.dong.framework.tool.SecurityCode; 8 import com.dong.framework.tool.SecurityImage; 9 10 /**11  * 提供图片验证码12  * @version 1.0 2012/08/2213  * @author dongliyang14  */15 @SuppressWarnings("serial")16 public class SecurityCodeImageAction extends ActionSupport implements SessionAware{17     18     //Struts2中Map类型的session19     private Map<String, Object> session;20     21     //图片流22     private ByteArrayInputStream imageStream;23 24     public ByteArrayInputStream getImageStream() {25         return imageStream;26     }27 28     public void setImageStream(ByteArrayInputStream imageStream) {29         this.imageStream = imageStream;30     }31 32     33     public String execute() throws Exception {34         //如果开启Hard模式,可以不区分大小写35 //        String securityCode = SecurityCode.getSecurityCode(4,SecurityCodeLevel.Hard, false).toLowerCase();36         37         //获取默认难度和长度的验证码38         String securityCode = SecurityCode.getSecurityCode();39         imageStream = SecurityImage.getImageAsInputStream(securityCode);40         //放入session中41         session.put("SESSION_SECURITY_CODE", securityCode);42         return SUCCESS;43     }44 45     public void setSession(Map<String, Object> session) {46         this.session = session;47     }48 49 }
复制代码

 

  2)Struts.xml

   在 Struts.xml配置文件中,需要配置SecurityCodeImageAction,由于现在返回的是流,就不应该再使用普通的方式了,应该在result上加上type="stream"。

  同时<param name="inputName">这一项的值,应该与SecurityCodeImageAction中的图片流名称一致。

    Struts.xml:

复制代码
 1 <package name="Security" namespace="/Security" extends="struts-default"> 2     <action name="SecurityCodeImageAction"  3     class="com.dong.security.action.SecurityCodeImageAction"> 4         <result name="success" type="stream"> 5             <param name="contentType">image/jpeg</param> 6             <param name="inputName">imageStream</param> 7             <param name="bufferSize">2048</param> 8         </result> 9     </action>10 </package>
复制代码

 

  3)前台JSP

  定义一个img元素,将src指向SecurityCodeImageAction就可以了,浏览器向Action发送请求,服务器将图片流返回,图片就能够显示了。

1 <img src="Security/SecurityCodeImageAction" id="Verify"  style="cursor:hand;" alt="看不清,换一张"/>2 <input type="text" name="securityCode"/>

  4)JS

      验证码一般都有点击刷新的功能,这个也容易实现,点击图片,重新给图片的src赋值。但是这时,浏览器会有缓存问题,如果浏览器发现src中的url不变,就认为图片没有改变,就会使用缓存中的图片,而不是重新向服务器请求。解决办法是在url后面加上一个时间戳,每次点击时,时间戳都不一样,浏览器就认为是新的图片,然后就发送请求了。

     jQuery:

复制代码
1 $(function () {  2     //点击图片更换验证码3     $("#Verify").click(function(){4         $(this).attr("src","SecurityCodeImageAction?timestamp="+new Date().getTime());5     });6 });
复制代码

   

      JavaScript: 

复制代码
1 window.onload=function(){2     var verifyObj = document.getElementById("Verify");3     verifyObj.onclick=function(){4         this.src="SecurityCodeImageAction?timestamp="+new Date().getTime();5     };6 }
复制代码

     5) 登录Action     现在可以模拟登录了,为了简单起见,不进行数据库操作,只判断了验证码是否匹配。

复制代码
 1 package com.dong.security.action; 2  3 import java.util.Map; 4 import org.apache.struts2.interceptor.SessionAware; 5 import com.opensymphony.xwork2.ActionSupport; 6  7 /** 8  * 用户登录Action 9  * @version 1.010  * @author dongliyang11  *12  */13 @SuppressWarnings("serial")14 public class LoginAction extends ActionSupport implements SessionAware{15     16     //Struts2中Map类型的session17     private Map<String, Object> session;18     //接收客户端传来的验证码19     private String securityCode;20     21     /**22      * 用户登录23      * @return String24      */25     public String login(){26         27         String serverCode = (String)session.get("SESSION_SECURITY_CODE");28         if(!serverCode.equals(securityCode)){29             return ERROR;30         }31         32         //继续判断用户名和密码,这个简单的例子就省略了33         34         return SUCCESS;35     }36 37     public void setSession(Map<String, Object> session) {38         this.session = session;39     }40     41     public String getSecurityCode() {42         return securityCode;43     }44 45     public void setSecurityCode(String securityCode) {46         this.securityCode = securityCode;47     }48 }
复制代码

 

  6)效果

     生成的验证码图片如下所示,浅蓝色的字体,浅灰色的噪点。

   

                图:验证码

 

   结束: 经过上面的三个步骤,Struts2 结合验证码的例子就介绍完了。

http://www.cnblogs.com/dongliyang/archive/2012/08/24/2654431.html(转载连接)

原创粉丝点击