生成验证码的方式有很多,个人认为较为灵活方便的是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. [原创] 绿色单文件封装程序GreenOne V3.0

    1.原理 将包含可执行文件的多个文件 调用Winrar,创建自解压格式压缩文件 设置高级自解压选项中的文本和图标,设置解压后运行的文件为选中的可执行文件. 这种创建单文件封装其实也就是一个Winrar ...

  2. Spring框架 jar包下载

    Spring框架下载 打开网址https://repo.spring.io 点击左侧边栏第二个按钮 点击 在输入框输入spring-framework点击Search 找到你需要的版本下载就好 教程到 ...

  3. redis持久化快速回忆手册

    Redis提供的持久化机制: 1). RDB持久化:该机制是指在指定的时间间隔内将内存中的数据集快照写入磁盘. 2). AOF持久化:该机制将以日志的形式记录服务器所处理的每一个写操作,在Redis服 ...

  4. 前端 tips

    1.==和!=操作符会在需要的情况下自动转换数据类型.但===和!==不会,它们会同时比较值和数据类型,这也使得它们要比==和!=快. 2.首次为变量赋值时务必使用var关键字,变量没有声明而直接赋值 ...

  5. jdbc(2)

    create table account ( id int primary key auto_increment, name varchar(20), money double);insert int ...

  6. struts和struts2的区别

    1.Structs2简介和Structs2开发环境搭建 一.Structs2简介: 1.什么是Struct2? 著名的SSH三大框架分别为:表现层(Structs).业务逻辑层(Spring),持久化 ...

  7. MyBatis之级联小结

    在这之前我们知道了MyBatis为我们提供了三种级联:一对一关系(assocation).一对多关系(collection).鉴别器(discriminator).在最后一个鉴别器例子中,看到了当层级 ...

  8. Reverse Integer 2015年6月23日

    题目: Reverse digits of an integer. Example1: x = , return Example2: x = -, return - 思路:递归 解答: / test ...

  9. Jmeter结构体系及运行原理

    Jmeter结构体系 把Jmeter的结构体系拆分为三维空间,如图: X1~X5:是负载模拟的一个过程,使用这些组件来完成负载的模拟: X1:选择协议,模拟用户请求,检查服务器响应是否正确,然后收集结 ...

  10. 《JAVA与模式》之命令模式

    在阎宏博士的<JAVA与模式>一书中开头是这样描述命令(Command)模式的: 命令模式属于对象的行为模式.命令模式又称为行动(Action)模式或交易(Transaction)模式. ...