kaptcha 是一个扩展自 simplecaptcha 的验证码库,方便我们不再写此类功能。
他的代码是谷歌托管的,可以从这里下载http://code.google.com/p/kaptcha/
工程内已经附带了示例,可以方便开发者使用。
需要的操作就是把kaptcha-2.3.2.jar增加到工程内,然后配置访问图片的Servlet:
示例中的配置是:
Kaptcha
/Kaptcha.jpg
也就是说访问Kaptcha.jpg时其实就是访问了输出验证码图片的Servlet。
示例中的KaptchaExample.jsp是调用页面,这里介绍了如何验证用户输入是否和验证码符合。
但是没有如何刷新的操作,刷新其实很简单,这里稍微修改即可。
注意,必须加随机参数,否则读取缓存就不会有效果。
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
Kaptcha Examplefunction refImg(){
document.getElementById("Kaptcha").src="Kaptcha.jpg?data="+Math.random();
}
Kaptcha.jpg" οnclick="refImg()"> |
|
String c = (String)session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
String parm = (String) request.getParameter("kaptchafield");
out.println("Parameter: " + parm + " ? Session Key: " + c + " : ");
if (c != null && parm != null) {
if (c.equals(parm)) {
out.println("true");
} else {
out.println("false");
}
}
%>
另外修改后使用的是绝对路径,在实际开发中应该注意这个问题。
做示例时使用的是kaptcha-2.3.2,见附件。