掌握Kaptcha验证码库的使用技巧,轻松集成至项目中
kaptcha 是一个扩展自 simplecaptcha 的验证码库,方便我们不再写此类功能。 他的代码是谷歌托管的,可以从这里下载 工程内已经附带了示例,可以方便开发者使用。
需要的操作就是把kaptcha-2.3.2.jar增加到工程内,然后配置访问图片的Servlet: 示例中的配置是:
-
- [servlet-mapping]
- [servlet-name]Kaptcha[/servlet-name]
- [url-pattern]/Kaptcha.jpg[/url-pattern]
- [/servlet-mapping]
复制代码
也就是说访问Kaptcha.jpg时其实就是访问了输出验证码图片的Servlet。 示例中的KaptchaExample.jsp是调用页面,这里介绍了如何验证用户输入是否和验证码符合。 但是没有如何刷新的操作,刷新其实很简单,这里稍微修改即可。 注意,必须加随机参数,否则读取缓存就不会有效果。
-
- [%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %]
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://" +request.getServerName()+":" +request.getServerPort()+path+"/"
- [html]
- [head]
- [meta http-equiv="Content-Type" content="text/html; charset=UTF-8"]
- [title]Kaptcha Example[/title]
- [script type="text/javascript"]
- function refImg(){
- document.getElementById("Kaptcha").src="<%=basePath%>Kaptcha.jpg?data="+Math.random();
- }
- [/script]
- [/head]
- [body]
- [table]
- [tr]
- [td][img id="Kaptcha" src="<%=basePath%>Kaptcha.jpg" alt="掌握Kaptcha验证码库的使用技巧,轻松集成至项目中" onclick="refImg()"][/td]
- [td valign="top"]
- [form method="POST"]
- [br]sec code:[input type="text" name="kaptchafield"][br/]
- [input type="submit" name="submit"]
- [/form]
- [/td]
- [/tr]
- [/table]
- [br/]
- [%
- 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("[b]true[/b]");
- } else {
- out.println("[b]false[/b]");
- }
- }
- %]
- [/body]
- [/html]
复制代码
另外修改后使用的是绝对路径,在实际开发中应该注意这个问题。 做示例时使用的是kaptcha-2.3.2,见附件。
|