如何通过Kaptcha在Web页面生成验证码

kaptcha 是一个扩展自 simplecaptcha 的验证码库,方便我们不再写此类功能。

他的代码是谷歌托管的,可以从这里下载http://code.google.com/p/kaptcha/

工程内已经附带了示例,可以方便开发者使用。

需要的操作就是把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" 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,见附件。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
  • Google Kaptcha 框架实现登录验证码功能(SSM 和 SpringBoot)
  • 使用google.kaptcha来生成图片验证码的实现方法
  • SpringBoot集成kaptcha验证码
  • spring整合kaptcha验证码的实现
  • SpringMvc使用GoogleKaptcha生成验证码
  • SpringBoot 集成Kaptcha实现验证码功能实例详解
  • 登陆验证码kaptcha结合spring boot的用法详解
  • java验证码组件kaptcha使用方法

转载请注明出处:http://www.mlhpz.com/article/20230503/138454.html