現在有不少網站在使用者填寫表單時,同時要求填寫驗證碼,驗證碼的一個目的就是防範一些惡意的網站下載軟體,這些軟體能通過遍曆連結而將網站的所有網頁下載。還可以防止使用者不經過本網站的頁面而使用網站的資源。所以現在有不少網站都使用了驗證碼技術,驗證碼通常是一個在WEB伺服器上產生的隨機字串,同時以某種方式儲存起來,比如儲存到與當前的Session中,然後在使用者提交網頁時與使用者輸入的驗證比較是否一致,然而如果直接以明文的方式,還是不能防範一些功能較強的自動填寫表格的軟體。所以一般將驗證碼以圖片的形式顯示出來,同時可以將在圖片中顯示的字串進行一些處理,比如使用旋轉字元,添加背景材質等技術以增大被軟體識別的難度。下面簡要介紹一下如果實現這種驗證碼:首先實現一個servlet用來產生圖片(當然也可以用jsp實現):
package untitled7;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.sun.image.codec.jpeg.*;
import java.awt.*;
import com.sun.image.codec.jpeg.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.geom.GeneralPath;
import javax.swing.*;
import java.math.*;
public class Servlet1
extends HttpServlet ...{
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException ...{
response.setContentType(request.getContentType());
response.setContentType("image/jpeg"); //必須設定ContentType為image/jpeg
int length = 4; //設定預設產生4個數字
Date d = new Date();
long lseed = d.getTime();
java.util.Random r = new Random(lseed); //設定隨機種子
if (request.getParameter("length") != null) ...{
try ...{
length = Integer.parseInt(request.getParameter("length"));
}
catch (NumberFormatException e) ...{
}
}
StringBuffer str = new StringBuffer();
for (int i = 0; i < length; i++) ...{
str.append(r.nextInt(9)); //產生隨機數字
}
//可以在此加入儲存驗證碼的代碼
//建立記憶體配置圖像
BufferedImage bi = new BufferedImage(40, 16, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.clearRect(0, 0, 16, 40);
g.setColor(Color.RED);
g.drawString(str.toString(), 4, 12);
try ...{
//使用JPEG編碼,輸出到response的輸出資料流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.
getOutputStream());
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
param.setQuality(1.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(bi);
}
catch (Exception ex) ...{
}
}
}
然後在需求顯示驗證碼的加入以下代碼就可以了
| <img alt="" src="/WebModule1/servlet1" width="40" height="16"/> |