设为首页 加入收藏

TOP

Spring MVC 中使用 kaptcha 验证码(一)
2017-06-22 10:23:53 】 浏览:451
Tags:Spring MVC 使用 kaptcha 验证

生成验证码的方式有很多,个人认为较为灵活方便的是Kaptcha ,他是基于SimpleCaptcha的开源项目。使用Kaptcha 生成验证码十分简单并且参数可以进行自定义。只需添加jar包配置下就可以使用。kaptcha所有配置都可以通过web.xml来完成,如果项目使用了Spring MVC,那么实现方式会略有不同。


一、Servlet项目


1、添加jar包依赖


maven项目,在pom.xml中添加dependency


<!-- kaptcha --> 
<dependency> 
    <groupId>com.google.code.kaptcha</groupId> 
    <artifactId>kaptcha</artifactId> 
    <version>2.3.2</version> 
</dependency>


非maven项目,在官网下载kaptcha的jar包,然后添加到项目lib库中。


下载地址:http://code.google.com/p/kaptcha/downloads/list


2、配置web.xml


<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>


注:url-pattern 自定义


kaptcha的参数都有默认值,如果要配置kaptcha,在init-param增加响应的参数即可


<servlet> 
    <servlet-name>Kaptcha</servlet-name> 
    <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> 
    <init-param> 
        <param-name>kaptcha.image.width</param-name> 
        <param-value>200</param-value> 
        <description>Width in pixels of the kaptcha image.</description> 
    </init-param> 
    <init-param> 
        <param-name>kaptcha.image.height</param-name> 
        <param-value>50</param-value> 
        <description>Height in pixels of the kaptcha image.</description> 
    </init-param> 
    <init-param> 
        <param-name>kaptcha.textproducer.char.length</param-name> 
        <param-value>4</param-value> 
        <description>The number of characters to display.</description> 
    </init-param> 
    <init-param> 
        <param-name>kaptcha.noise.impl</param-name> 
        <param-value>com.google.code.kaptcha.impl.NoNoise</param-value> 
        <description>The noise producer.</description> 
    </init-param> 
</servlet>


3、jsp代码


<script type="text/java script">
$(function(){  //生成验证码       
    $('#kaptchaImage').click(function () { 
    $(this).hide().attr('src', '/code/captcha-image?' + Math.floor(Math.random()*100) ).fadeIn(); });     
}); 
 
window.onbeforeunload = function(){ 
    //关闭窗口时自动退出 
    if(event.clientX>360&&am

首页 上一页 1 2 3 4 下一页 尾页 1/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C语言如何分离一个数的高低位,如.. 下一篇Java中抽象类的定义和使用

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目