本文分三個步驟介紹驗證碼圖片生成以及與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-1 72 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-1 80 int r=(int)(Math.random()*n); 81 82 //將result中的第i個元素設置為codes[r]存放的數值 83 result[i]=codes[r]; 84 85 //必須確保不會再次抽取到那個字符,因為所有抽取的字符必須不相同。 86 //因此,這里用數組中的最后一個字符改寫codes[r],並將n減1 87 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/22 13 * @author dongliyang 14 */ 15 @SuppressWarnings("serial") 16 public class SecurityCodeImageAction extends ActionSupport implements SessionAware{ 17 18 //Struts2中Map類型的session 19 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.0 10 * @author dongliyang 11 * 12 */ 13 @SuppressWarnings("serial") 14 public class LoginAction extends ActionSupport implements SessionAware{ 15 16 //Struts2中Map類型的session 17 private Map<String, Object> session; 18 //接收客戶端傳來的驗證碼 19 private String securityCode; 20 21 /** 22 * 用戶登錄 23 * @return String 24 */ 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 結合驗證碼的例子就介紹完了。
#########
修改日志:
2012/12/28 修改了文章中不嚴謹的地方。
2013/07/24 留言中有網友反饋說,請求不到圖片。 可能是struts.xml配置上有點問題。
原來文章中寫的是extends="struts2"。這個"strtus2"是項目中配置的,所以出現了問題。
更正:
SecurityCodeImageAction的配置文件struts.xml中
<package name="Security" namespace="/Security" extends="struts2">
改為
<package name="Security" namespace="/Security" extends="struts-default">