验证码插件kaptcha的jsp使用

1,去http://code.google.com/p/kaptcha/downloads/list下载kaptcha-2.3.2.zip包,或直接【点此下载】解压交其中的kaptcha-2.3.2.jar 导入项目目录下lib

2,向web.xml里添加servlet

<servlet>
<servlet-name>Kaptcha</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>

</servlet>
<servlet-mapping>
<servlet-name>Kaptcha</servlet-name>
<url-pattern>/kaptcha.jpg</url-pattern>
</servlet-mapping>


3,服务端程序验证功能

@RequestMapping("/kaptcha.do")
public void kaptcha(HttpServletRequest request, HttpServletResponse response) {
String kaptchaExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
String kaptchaReceived = request.getParameter("kaptcha"); //获取填写的验证码内容
if (kaptchaReceived == null || !kaptchaReceived.equalsIgnoreCase(kaptchaExpected)) { //判断内容是否相同
try {
response.getWriter().print("validation code is wrong.");
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
response.getWriter().print("validation code is right.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

4,jsp代码

为了便于测试。本文用JQuery添加属性

<script type="text/javascript" src="page/js/jquery.js"></script>
<script type="text/javascript">
$(function(){
$('#kaptchaImage').click(function () {
$(this).attr('src', 'kaptcha.jpg?' + Math.floor(Math.random()*100) );
});
});
</script>
 <form action="kaptcha.do">
<img src="kaptcha.jpg" id="kaptchaImage"/>
<input type="text" name="kaptcha" value=""/><br/>
<button type="submit">提交</button>
 </form>




 

 

 



你可能感兴趣的:(kaptcha)