原理如下:
1.寫一個類產生圖片檔案(Image.java)
2.寫一個jsp檔案,用於產生圖片(createimage.jsp)
3.寫一個首頁面,用於顯示圖片驗證碼(image.jsp)
4.寫一個jsp檔案,動態載入圖片,用於更換圖片驗證碼(imagesrc.jsp)
5.寫一個驗證圖片驗證碼是否正確的jsp檔案
在image.jsp中擷取createimage.jsp中產生的圖片,然後顯示出來,點擊更換圖片的時候,自動在顯示圖片的<td>中載入imagesrc.jsp頁面的內容
(該頁面只包含一個圖片),因為瀏覽器不會重複訪問同一URL的資源,所以每次訪問createimage.jsp時在後面追加一個時間戳記,於是在image.jsp中不用重新整理整個頁面便可更換圖片驗證碼了,每次擷取驗證碼時,將驗證碼圖片中包含的字串值存入session中,在使用者填寫擷取的驗證碼後提交時,通過JavaScript將使用者填寫的內容與session中的值比較,正確則提交成功,否則提交失敗。
代碼如下:
1、產生圖片的Java類:Image.java
package test.image; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletResponse; public class Image { HttpServletResponse response ; // 驗證碼圖片中可以出現的字元集,可根據需要修改 private char mapTable[] = { 'a', 'b', 'c', 'd', 'e', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0','1', '2', '3', '4', '5', '6', '7', '8', '9','A','B','C','D','E','F','G', 'H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; public Image(HttpServletResponse response){ this.response = response ; } public String getCertPic(int width, int height) { if (width <= 0) { width = 60; } if (height <= 0) { height = 20; } BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 擷取圖形上下文 Graphics g = image.getGraphics(); // 設定背景顏色 g.setColor(new Color(0xDCDCDC)); g.fillRect(0, 0, width, height); // 畫邊框 g.setColor(Color.black); g.drawRect(0, 0, width - 1, height - 1); // 隨機產生的驗證碼 String strEnsure = ""; // 4代表4位驗證碼,如果要產生等多位的驗證碼 ,則加大數值 for (int i = 0; i < 4; i++) { strEnsure += mapTable[(int) (mapTable.length * Math.random())]; } // 將驗證碼顯示在映像中,如果要產生更多位的驗證碼,增加drawString語句 g.setColor(Color.red); g.setFont(new Font("Atlantic Inline", Font.PLAIN, 18)); String str = strEnsure.substring(0, 1); g.drawString(str, 8, 17); str = strEnsure.substring(1, 2); g.drawString(str, 20, 15); str = strEnsure.substring(2, 3); g.drawString(str, 35, 18); str = strEnsure.substring(3, 4); g.drawString(str, 45, 15); // 隨機產生10個幹擾點 Random random = new Random(); for (int i = 0; i < 10; i++) { int x = random.nextInt(width); int y = random.nextInt(height); g.drawOval(x, y, 1, 1); } // 釋放圖形上下文 g.dispose(); try { // 輸出映像到頁面 ImageIO.write(image, "JPEG", response.getOutputStream()); } catch (IOException e) { return ""; }finally{ try { response.getOutputStream().flush(); response.getOutputStream().close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return strEnsure; } }
2、產生圖片的jsp檔案 :createimage.jsp
<%@ page contentType="image/jpeg" import="test.image.*"%> <% response.setHeader("Pragma","No-cache"); response.setHeader("Cache-Control","no-cache"); response.setDateHeader("Expires", 0); Image image = new Image(response); String rs = image.getCertPic(60,20); session.setAttribute("imageString",rs); %>
3、顯示圖片驗證碼的頁面:image.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <% response.setHeader("Pragma","No-cache"); response.setHeader("Cache-Control","no-cache,must-revalidate"); response.setHeader("Expires","0"); %> <title>pictrue</title> <!-- <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css"> --> <mce:script type="text/javascript" src="../jslib/jquery-1.4.js" mce_src="jslib/jquery-1.4.js"></mce:script> <mce:script type="text/javascript" src="../jslib/imagecheck.js" mce_src="jslib/imagecheck.js"></mce:script> </head> <body> <center> <div id="tableDiv"> <table name="table" id="tab" border="0"> <tr> <td id="tdNode"> <input type="text" id="inputNode" name="image" maxlength="10"/> </td> <td id="imageNode"> <img src="createimage.jsp?asktime='<%=new Date() %>'" mce_src="createimage.jsp" /> </td> <td> <font size="2"><a href="#" mce_href="#" onclick="changeImage()">看不清楚,換一張</a></font> </td> </tr> <tr> <td colspan="3"><input type="button" value="validate" class="button" onclick="validate()"/></td> <td><input type="hidden" name="valid" id="val" value="0"/></td> </tr> </table> </div> </center> </body> </html>
4、用於載入動態圖片的頁面:imagesrc.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <mce:script type="text/javascript" src="../jslib/jquery-1.4.js" mce_src="jslib/jquery-1.4.js"></mce:script> </head> <body> <img name="image" src="createimage.jsp?asktime='<%=new Date() %>'"/> </body> </html>
5、擷取圖片驗證碼中字串內容的jsp檔案:
<%@ page language="java" pageEncoding="utf-8"%> <% out.print((String)session.getAttribute("imageString")); %>
image.jsp 的JavaScript代碼:
function changeImage(){ $("table").find("#imageNode").load("imagesrc.jsp"); } function validate(){ var text = $("table").find("#inputNode").attr("value"); $.ajax({ type:"POST", url:"getsession.jsp", success:function(msg){ msg = jQuery.trim(msg); if(msg==text){ alert("success"); }else{ alert("fail"); $("table").find("#inputNode").focus(); } } }); }
寫完這些必要的檔案後,便可以在瀏覽器上驗證了.