转自:http://my.oschina.net/CandyDesire/blog/209364

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

一、Servlet项目

1、添加jar包依赖

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

1
2
3
4
5
6
<!-- 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

1
2
3
4
5
6
7
8
<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增加响应的参数即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<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代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<script type="text/javascript"
$(function(){  //生成验证码         
    $('#kaptchaImage').click(function () {  
    $(this).hide().attr('src''/code/captcha-image?' + Math.floor(Math.random()*100) ).fadeIn(); });      
});   
 
window.onbeforeunload = function(){  
    //关闭窗口时自动退出  
    if(event.clientX>360&&event.clientY<0||event.altKey){     
        alert(parent.document.location);  
    }  
};  
             
function changeCode() {  //刷新
    $('#kaptchaImage').hide().attr('src''/code/captcha-image?' + Math.floor(Math.random()*100) ).fadeIn();  
    event.cancelBubble=true;  
}  
</script> 
 
<div class="form-group">  
   <label>验证码 </label> 
   <input name="j_code" type="text" id="kaptcha" maxlength="4" class="form-control" />
   <br/> 
   <img src="/code/captcha-image" id="kaptchaImage"  style="margin-bottom: -3px"/>       
   <a href="#" onclick="changeCode()">看不清?换一张</a>  
</div>

二、Spring mvc 中使用kaptcha

1、spring 配置文件 applicationContext.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">  
        <property name="config">  
            <bean class="com.google.code.kaptcha.util.Config">  
                <constructor-arg>  
                    <props>  
                        <prop key="kaptcha.border">yes</prop>  
                        <prop key="kaptcha.border.color">105,179,90</prop>  
                        <prop key="kaptcha.textproducer.font.color">blue</prop>  
                        <prop key="kaptcha.image.width">125</prop>  
                        <prop key="kaptcha.image.height">45</prop>  
                        <prop key="kaptcha.textproducer.font.size">45</prop>  
                        <prop key="kaptcha.session.key">code</prop>  
                        <prop key="kaptcha.textproducer.char.length">4</prop>  
                        <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>  
                    </props>  
                </constructor-arg>  
            </bean>  
        </property>  
    </bean>

2、Controller的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.awt.image.BufferedImage;  
import javax.imageio.ImageIO;  
import javax.servlet.ServletOutputStream;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.http.HttpSession;   
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.servlet.ModelAndView;  
import com.google.code.kaptcha.Constants;  
import com.google.code.kaptcha.Producer;  
  
@Controller  
@RequestMapping("/code")  
public class CaptchaController {  
       
    @Autowired  
    private Producer captchaProducer = null;  
   
    @RequestMapping(value = "captcha-image")  
    public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {  
        HttpSession session = request.getSession();  
        String code = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);  
        System.out.println("验证码: " + code );  
           
        response.setDateHeader("Expires"0);  
        response.setHeader("Cache-Control""no-store, no-cache, must-revalidate");  
        response.addHeader("Cache-Control""post-check=0, pre-check=0");  
        response.setHeader("Pragma""no-cache");  
        response.setContentType("image/jpeg");  
         
        String capText = captchaProducer.createText();  
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);  
         
        BufferedImage bi = captchaProducer.createImage(capText);  
        ServletOutputStream out = response.getOutputStream();  
        ImageIO.write(bi, "jpg", out);  
        try {  
            out.flush();  
        finally {  
            out.close();  
        }  
        return null;  
    }  
}

3、kaptcha可配置项

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
kaptcha.border  是否有边框  默认为true  我们可以自己设置yes,no  
kaptcha.border.color   边框颜色   默认为Color.BLACK  
kaptcha.border.thickness  边框粗细度  默认为1  
kaptcha.producer.impl   验证码生成器  默认为DefaultKaptcha  
kaptcha.textproducer.impl   验证码文本生成器  默认为DefaultTextCreator  
kaptcha.textproducer.char.string   验证码文本字符内容范围  默认为abcde2345678gfynmnpwx  
kaptcha.textproducer.char.length   验证码文本字符长度  默认为5  
kaptcha.textproducer.font.names    验证码文本字体样式  默认为new Font("Arial"1, fontSize), new Font("Courier"1, fontSize)  
kaptcha.textproducer.font.size   验证码文本字符大小  默认为40  
kaptcha.textproducer.font.color  验证码文本字符颜色  默认为Color.BLACK  
kaptcha.textproducer.char.space  验证码文本字符间距  默认为2  
kaptcha.noise.impl    验证码噪点生成对象  默认为DefaultNoise  
kaptcha.noise.color   验证码噪点颜色   默认为Color.BLACK  
kaptcha.obscurificator.impl   验证码样式引擎  默认为WaterRipple  
kaptcha.word.impl   验证码文本字符渲染   默认为DefaultWordRenderer  
kaptcha.background.impl   验证码背景生成器   默认为DefaultBackground  
kaptcha.background.clear.from   验证码背景颜色渐进   默认为Color.LIGHT_GRAY  
kaptcha.background.clear.to   验证码背景颜色渐进   默认为Color.WHITE  
kaptcha.image.width   验证码图片宽度  默认为200  
kaptcha.image.height  验证码图片高度  默认为50

 

kaptcha Spring 整合的更多相关文章

  1. 使用Spring整合Quartz轻松完成定时任务

    一.背景 上次我们介绍了如何使用Spring Task进行完成定时任务的编写,这次我们使用Spring整合Quartz的方式来再一次实现定时任务的开发,以下奉上开发步骤及注意事项等. 二.开发环境及必 ...

  2. 【Java EE 学习 53】【Spring学习第五天】【Spring整合Hibernate】【Spring整合Hibernate、Struts2】【问题:整合hibernate之后事务不能回滚】

    一.Spring整合Hibernate 1.如果一个DAO 类继承了HibernateDaoSupport,只需要在spring配置文件中注入SessionFactory就可以了:如果一个DAO类没有 ...

  3. spring整合hibernate的详细步骤

    Spring整合hibernate需要整合些什么? 由IOC容器来生成hibernate的sessionFactory. 让hibernate使用spring的声明式事务 整合步骤: 加入hibern ...

  4. Spring整合Ehcache管理缓存

    前言 Ehcache 是一个成熟的缓存框架,你可以直接使用它来管理你的缓存. Spring 提供了对缓存功能的抽象:即允许绑定不同的缓存解决方案(如Ehcache),但本身不直接提供缓存功能的实现.它 ...

  5. spring整合hibernate

    spring整合hibernate包括三部分:hibernate的配置.hibernate核心对象交给spring管理.事务由AOP控制 好处: 由java代码进行配置,摆脱硬编码,连接数据库等信息更 ...

  6. MyBatis学习(四)MyBatis和Spring整合

    MyBatis和Spring整合 思路 1.让spring管理SqlSessionFactory 2.让spring管理mapper对象和dao. 使用spring和mybatis整合开发mapper ...

  7. Mybatis与Spring整合,使用了maven管理项目,作为初学者觉得不错,转载下来

    转载自:http://www.cnblogs.com/xdp-gacl/p/4271627.html 一.搭建开发环境 1.1.使用Maven创建Web项目 执行如下命令: mvn archetype ...

  8. Spring整合HBase

    Spring整合HBase Spring HBase SHDP § 系统环境 § 配置HBase运行环境 § 配置Hadoop § 配置HBase § 启动Hadoop和HBase § 创建Maven ...

  9. Spring整合Ehcache管理缓存(转)

    目录 前言 概述 安装 Ehcache的使用 HelloWorld范例 Ehcache基本操作 创建CacheManager 添加缓存 删除缓存 实现基本缓存操作 缓存配置 xml方式 API方式 S ...

随机推荐

  1. AIX用户和组管理

    1.用户登录和初始化

  2. PAT Advanced 1048 Find Coins (25 分)

    Eva loves to collect coins from all over the universe, including some other planets like Mars. One d ...

  3. PAT Advanced 1041 Be Unique (20 分)

    Being unique is so important to people on Mars that even their lottery is designed in a unique way. ...

  4. 洛谷P3374 【模板】树状数组 1&&P3368 【模板】树状数组 2题解

    图片来自度娘~~ 树状数组形如上图,是一种快速查找区间和,快速修改的一种数据结构,一个查询和修改复杂度都为log(n),树状数组1和树状数组2都是板子题,在这里进行详解: 求和: 首先我们看一看这个图 ...

  5. numpy模块、matplotlib模块、pandas模块

    目录 1. numpy模块 2. matplotlib模块 3. pandas模块 1. numpy模块 numpy模块的作用 用来做数据分析,对numpy数组(既有行又有列)--矩阵进行科学计算 实 ...

  6. iOS自定义键盘的简单实现

    自定义键盘类VolumeInputKeyboardView: VolumeInputKeyboardView.h文件: #import <UIKit/UIKit.h> NS_ASSUME_ ...

  7. jmeter测试文件上传功能

    最近为了完成自动化KPI开始慢慢接触jmeter,其中遇到了不少问题,今天就遇到了文件上传的问题,在这里记录下加深记忆,也可供jmeter初级使用者作为一个参考.另外论坛上已有同事发过关于jmeter ...

  8. SpringCloud微服务面试题

    spring data是spring用于简化spring开发中数据访问操作的项目spring Dataspring Data为我们提供了使用统一的API来对数据访问层进行操作,这主要是Spring D ...

  9. 树莓派Zero W无键盘无屏幕初始化

    买了个树莓派Zero W,结果发现没mini hdmi线 淘宝了一根mini hdmi,等了5天,拿到手后发现zero还没地接键盘,这下脑袋大了 查了下资料,发现树莓的系统,可以这boot分区中加入一 ...

  10. 【leetcode】1184. Distance Between Bus Stops

    题目如下: A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between al ...