生成验证码的方式有很多,个人认为较为灵活方便的是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/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

<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的实现

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可配置项

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

Spring mvc 中使用 kaptcha 验证码的更多相关文章

  1. Spring mvc中@RequestMapping 6个基本用法

    Spring mvc中@RequestMapping 6个基本用法 spring mvc中的@RequestMapping的用法.  1)最基本的,方法级别上应用,例如: Java代码 @Reques ...

  2. spring mvc中使用freemark的一点心得

    参考文档: FreeMarker标签与使用 连接http://blog.csdn.net/nengyu/article/details/6829244 freemarker学习笔记--指令参考: ht ...

  3. Http请求中Content-Type讲解以及在Spring MVC中的应用

    引言: 在Http请求中,我们每天都在使用Content-type来指定不同格式的请求信息,但是却很少有人去全面了解content-type中允许的值有多少,这里将讲解Content-Type的可用值 ...

  4. Spring mvc中@RequestMapping 6个基本用法小结(转载)

    小结下spring mvc中的@RequestMapping的用法. 1)最基本的,方法级别上应用,例如: @RequestMapping(value="/departments" ...

  5. Spring MVC中处理静态资源的多种方法

    处理静态资源,我想这可能是框架搭建完成之后Web开发的”头等大事“了. 因为一个网站的显示肯定会依赖各种资源:脚本.图片等,那么问题来了,如何在页面中请求这些静态资源呢? 还记得Spring MVC中 ...

  6. Spring MVC 中的基于注解的 Controller【转】

    原文地址:http://my.oschina.net/abian/blog/128028 终于来到了基于注解的 Spring MVC 了.之前我们所讲到的 handler,需要根据 url 并通过 H ...

  7. spring mvc中的文件上传

    使用commons-fileupload上传文件所需要的架包有:commons-fileupload 和common-io两个架包支持,可以到Apache官网下砸. 在配置文件spring-mvc.x ...

  8. spring mvc中的valid

    当你希望在spring mvc中直接校验表单参数时,你可以采用如下操作: 声明Validator的方式: 1.为每一个Controller声明一个Validator @Controller publi ...

  9. spring mvc中的@PathVariable(转)

    鸣谢:http://jackyrong.iteye.com/blog/2059307 ------------------------------------------------ spring m ...

随机推荐

  1. PHP 安装 Xdebug 扩展(一)

    一.前言 1. Xdebug 简介 Xdebug 是一个开放源代码的 PHP 程序调试器(即一个Debug工具),可以用来跟踪,调试和分析PHP程序的运行状况.当前最新版本为 Xdebug 2.5.0 ...

  2. MyEclipse(8.5以上的版本) 安装js的开发插件aptana

    最近在学习js,想在MyEclipse(MyEclipse 10) 上面安装一个js的开发的插件aptana. MyEclipse 8.5以后的版本的安装的方法: 1.下载aptana_update_ ...

  3. 有些arp请求报文中为什么会有目的mac地址(不使用广播地址)

    有些arp请求报文中为什么会有目的mac地址(不使用广播地址) 最近做实验,注意到局域网内大部分的arp包的以太网头部目的mac地址并不是广播地址,并且包内的目的mac地址字段并不是全0,而是目的ip ...

  4. Android计时器 android.widget.Chronometer

    说起做定时器,大家一般会想到Timer和Executors的定时器线程池,其实用这两个做都会有问题,在停止和重新计时时你回发现无法停止或者说计时加快(加快是因为多个线程在记录同一个变量),Androi ...

  5. dp

    1. 将原问题分解为子问题 2. 确定状态 3. 确定一些初始状态(边界状态)的值 4. 确定状态转移方程 1) 问题具有最优子结构性质.如果问题的最优解所包含的子问题的解也是最优的,我们就称该问题具 ...

  6. JS判断PC和移动端设备

    1.方法一 function IsPC() { var userAgentInfo = navigator.userAgent; var Agents = ["Android", ...

  7. [刷题]算法竞赛入门经典(第2版) 5-11/UVa12504 - Updating a Dictionary

    题意:对比新老字典的区别:内容多了.少了还是修改了. 代码:(Accepted,0.000s) //UVa12504 - Updating a Dictionary //#define _XieNao ...

  8. javaweb之监听器详解

    在servlet中定义了多种类型的监听器,他们用于监听事件源分别是servletContext,httpsession,servletrequest 这三个域对象. servlet中监听器主要有三类: ...

  9. Html标签,file方式,上传文件

    恩,如果不记下来,记忆就会模糊掉. 希望自己下次看见这篇博客的时候,会解决掉疑问 ----------------------------------------------------------- ...

  10. php 使用composer

    之前写过相关的composer,之后碰到了几个朋友问我,我整理了一下,方便自己也方便大家日后查阅~~不玩开源的程序员不是好厨子     1.执行在线安装         curl -sS https: ...