Struts2 驗證碼圖片生成實例

Step 1.隨機驗證碼

一步一步來,要生成驗證碼圖片,首先要有驗證碼,然後才能在畫在圖片上。爲了能夠靈活控制驗證碼,特別編寫了SecurityCode類,它向外提供隨機字符串。並且可以控制字符串的長度和難度。SecurityCode類中提供的驗證碼分三個難度,易(全數字)、中(數字+小寫英文)、難(數字+大小寫英文)。難度使用枚舉SecurityCodeLevle表示,避免使用1、2、3這樣沒有明確意義的數字來區分。

  同時,還控制了能否出現重複的字符。爲了能夠方便使用,方法設計爲static。

  SecurityCode類:

[html] view plaincopy
  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 plaincopy
  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 plaincopy
  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 plaincopy
  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 plaincopy
  1. <img src="${ctx}/front/user/imagecode.action" id="Verify"  style="cursor:pointer;" alt="看不清,換一張"/>  

4)JS

      驗證碼一般都有點擊刷新的功能,這個也容易實現,點擊圖片,重新給圖片的src賦值。但是這時,瀏覽器會有緩存問題,如果瀏覽器發現src中的url不變,就認爲圖片沒有改變,就會使用緩存中的圖片,而不是重新向服務器請求。解決辦法是在url後面加上一個時間戳,每次點擊時,時間戳都不一樣,瀏覽器就認爲是新的圖片,然後就發送請求了。

     jQuery:

[html] view plaincopy
  1. $(function () {    
  2.       //點擊圖片更換驗證碼  
  3.     $("#Verify").click(function(){  
  4.             $(this).attr("src","${ctx}/front/user/imagecode.action?timestamp="+new Date().getTime());  
  5.         });  
  6.      });  

  5)效果

     生成的驗證碼圖片如下所示,淺藍色的字體,淺灰色的噪點。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章