• Struts2 验证码图片生成实例


    Step 1.随机验证码

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

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

      SecurityCode类:

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

    Step 2.图片

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

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

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

         SecurityImage类:

    [html] view plain copy
    1. package com.syz.onego.action.util;  
    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.  * 支持自定义验证码图片的大小;  
    18.  * 支持自定义需排除的特殊字符;  
    19.  * 支持自定义干扰线的数量;  
    20.  * 支持自定义验证码图文颜色  
    21.  * @author shiyz  
    22.  * @version 1.0   
    23.  */  
    24. public class SecurityImage {  
    25.          /**  
    26.            * 生成验证码图片  
    27.            * @param securityCode   验证码字符  
    28.            * @return  BufferedImage  图片  
    29.           */  
    30.          public static BufferedImage createImage(String securityCode){  
    31.              //验证码长度  
    32.              int codeLength=securityCode.length();  
    33.              //字体大小  
    34.             int fSize = 15;  
    35.               int fWidth = fSize + 1;  
    36.              //图片宽度  
    37.              int width = codeLength * fWidth + 6 ;  
    38.              //图片高度  
    39.              int height = fSize * 2 + 1;  
    40.               //图片  
    41.               BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
    42.               Graphics g=image.createGraphics();  
    43.              //设置背景色  
    44.               g.setColor(Color.WHITE);  
    45.                //填充背景  
    46.               g.fillRect(0, 0, width, height);  
    47.                //设置边框颜色  
    48.               g.setColor(Color.LIGHT_GRAY);  
    49.                //边框字体样式  
    50.               g.setFont(new Font("Arial", Font.BOLD, height - 2));  
    51.                //绘制边框  
    52.               g.drawRect(0, 0, width - 1, height -1);  
    53.                //绘制噪点  
    54.               Random rand = new Random();  
    55.                //设置噪点颜色  
    56.                g.setColor(Color.LIGHT_GRAY);  
    57.                for(int i = 0;i < codeLength * 6;i++){  
    58.                    int x = rand.nextInt(width);  
    59.                    int y = rand.nextInt(height);  
    60.                   //绘制1*1大小的矩形  
    61.                    g.drawRect(x, y, 1, 1);  
    62.                }  
    63.               //绘制验证码  
    64.              int codeY = height - 10;    
    65.               //设置字体颜色和样式  
    66.                g.setColor(new Color(19,148,246));  
    67.                g.setFont(new Font("Georgia", Font.BOLD, fSize));  
    68.                for(int i = 0; i < codeLength;i++){  
    69.                    g.drawString(String.valueOf(securityCode.charAt(i)), i * 16 + 5, codeY);  
    70.               }  
    71.                //关闭资源  
    72.                g.dispose();  
    73.                return image;  
    74.            }  
    75.            /**  
    76.            * 返回验证码图片的流格式  
    77.            * @param securityCode  验证码  
    78.             * @return ByteArrayInputStream 图片流  
    79.             */  
    80.            public static ByteArrayInputStream getImageAsInputStream(String securityCode){  
    81.              BufferedImage image = createImage(securityCode);  
    82.               return convertImageToStream(image);  
    83.           }  
    84.           /**  
    85.             * 将BufferedImage转换成ByteArrayInputStream  
    86.             * @param image  图片  
    87.             * @return ByteArrayInputStream 流  
    88.             */  
    89.            private static ByteArrayInputStream convertImageToStream(BufferedImage image){  
    90.              ByteArrayInputStream inputStream = null;  
    91.               ByteArrayOutputStream bos = new ByteArrayOutputStream();  
    92.              JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(bos);  
    93.               try {  
    94.                   jpeg.encode(image);  
    95.                   byte[] bts = bos.toByteArray();  
    96.                   inputStream = new ByteArrayInputStream(bts);  
    97.              } catch (ImageFormatException e) {  
    98.                   e.printStackTrace();  
    99.          } catch (IOException e) {  
    100.                  e.printStackTrace();  
    101.              }  
    102.              return inputStream;  
    103.          }  
    104. }  

    Step 3.验证码与Struts 2结合

      1)Action

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

          SecurityCodeImageAction类:

    [html] view plain copy
    1. package com.syz.onego.action.front.user;  
    2.   
    3. import java.io.ByteArrayInputStream;  
    4. import java.util.Map;  
    5.   
    6. import org.apache.struts2.convention.annotation.Action;  
    7. import org.apache.struts2.convention.annotation.Result;  
    8. import org.apache.struts2.convention.annotation.Results;  
    9. import org.apache.struts2.interceptor.SessionAware;  
    10.   
    11. import com.opensymphony.xwork2.ActionSupport;  
    12. import com.syz.onego.action.util.SecurityCode;  
    13. import com.syz.onego.action.util.SecurityImage;  
    14.   
    15. @Results({@Result(name = "success"type = "stream"params = {  
    16.         "contentType", "image/jpeg",  
    17.         "inputName", "imageStream",  
    18.         "bufferSize",  
    19.         "4096" })})  
    20. public class SecurityCodeImageAction  extends ActionSupport  implements SessionAware{  
    21.     private static final long serialVersionUID = 1496691731440581303L;  
    22.     //图片流  
    23.     private ByteArrayInputStream imageStream;  
    24.     //session域  
    25.     private Map<String, Object> session ;  
    26.       
    27.     public ByteArrayInputStream getImageStream() {  
    28.         return imageStream;  
    29.     }  
    30.     public void setImageStream(ByteArrayInputStream imageStream) {  
    31.         this.imageStream = imageStream;  
    32.     }  
    33.     public void setSession(Map<String, Object> session) {  
    34.         this.session = session;  
    35.     }  
    36.     @Action("imagecode")  
    37.     public String execute() throws Exception {  
    38.         //如果开启Hard模式,可以不区分大小写  
    39.         //String securityCode = SecurityCode.getSecurityCode(4,SecurityCodeLevel.Hard, false).toLowerCase();  
    40.           
    41.         //获取默认难度和长度的验证码  
    42.         String securityCode = SecurityCode.getSecurityCode();  
    43.         imageStream = SecurityImage.getImageAsInputStream(securityCode);  
    44.         //放入session中  
    45.         session.put("securityCode", securityCode);  
    46.         return SUCCESS;  
    47.     }  
    48. }  

    如果是配置文件的话:

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

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

        Struts.xml:

    [html] view plain copy
    1. <action name="SecurityCodeImageAction" class="securityCodeImageAction">  
    2.             <result name="success" type="stream">  
    3.                 <param name="contentType">image/jpeg</param>  
    4.                <param name="inputName">imageStream</param>  
    5.                <param name="bufferSize">2048</param>  
    6.             </result>  
    7. </action>  
    3)前台JSP

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

    [html] view plain copy
    1. <img src="${ctx}/front/user/imagecode.action" id="Verify"  style="cursor:pointer;" alt="看不清,换一张"/>  

    4)JS

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

         jQuery:

    [html] view plain copy
    1. $(function () {    
    2.       //点击图片更换验证码  
    3.     $("#Verify").click(function(){  
    4.             $(this).attr("src","${ctx}/front/user/imagecode.action?timestamp="+new Date().getTime());  
    5.         });  
    6.      });  

      5)效果

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






  • 相关阅读:
    Java关键字transient和volatile小结(转)
    1、环境
    SSH框架搭建
    2.4 easyui
    PHP操作大文件
    PHP小工具
    PHP正则替换函数收集
    PHP小知识收集
    Yii ACF(accessController)简单控权
    linux 文件存放目录
  • 原文地址:https://www.cnblogs.com/chenny3/p/10226221.html
Copyright © 2020-2023  润新知