下面是DLOG4J生成隨即驗證碼的代碼:
package dlog4j;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dlog4j.util.image.RandomImageGenerator;
/**
* 用于產生注冊用戶時的隨即圖片以防止非法攻擊
* @author Liudong
*/
public class RandomImageServlet extends HttpServlet {
public final static String RANDOM_LOGIN_KEY = "RANDOM_LOGIN_KEY";
public void init() throws ServletException {
System.setProperty("java.awt.headless","true");
}
public static String getRandomLoginKey(HttpServletRequest req) {
return (String)req.getSession().getAttribute(RANDOM_LOGIN_KEY);
}
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
HttpSession ssn = req.getSession();
if(ssn!=null) {
String randomString = RandomImageGenerator.random();
ssn.setAttribute(RANDOM_LOGIN_KEY,randomString);
res.setContentType("image/jpeg");
RandomImageGenerator.render(randomString,res.getOutputStream());
}
}
}
這段代碼在Linux下工作是沒問題的,但是生成圖片的時候會拋出類沒定義的異常,除非JDK是1.5版本。如果JDK為1.4的話,那只能給應用服務器的啟動加上參數-Djava.awt.headless=true,具體每個應用服務器如何加此參數請參照不同服務器的文檔。Tomcat可以通過修改startup.sh來添加這個參數。
在網上看過很多對該問題的描述,都沒有什么有效的解決辦法。