kaptchaCode(验证码)

1.springMVC-servlet.xml配置bean

<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.image.width">160</prop>  
                    <!-- 图片高度 -->
                    <prop key="kaptcha.image.height">50</prop>  
                    <prop key="kaptcha.session.key">code</prop>  
                    <!-- 设置字体颜色 -->
                    <prop key="kaptcha.textproducer.font.color">red</prop> 
                    <!-- 设置字体大小 --> 
                    <prop key="kaptcha.textproducer.font.size">35</prop>  
                    <!-- 文字价格 -->
                    <prop key="kaptcha.textproducer.char.space">5</prop>  
                     <!-- 设置字体个数 -->  
                    <prop key="kaptcha.textproducer.char.length">6</prop>  
                    <!-- 配置中文--> 
                    <!-- <prop key="kaptcha.textproducer.impl">com.google.code.kaptcha.text.impl.ChineseTextProducer</prop> -->
                    <!-- 设置字体样式 --> 
                    <prop key="kaptcha.textproducer.font.names">彩云,宋体,楷体,微软雅黑</prop>  
                </props>  
            </constructor-arg>  
        </bean>  
    </property>  
</bean> 

2.控制类VerifyCodeController.java

package com.shenqz.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 org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;  

import com.google.code.kaptcha.Constants;  
import com.google.code.kaptcha.Producer; 
  
/** 
 * 随机验证码控制层 
 *  
 * 使用kaptcha-2.3.2.jar支持 
 *  
 * @author shenqz
 *  
 */  
@Controller  
public class VerifyCodeController {  
    
    private Producer captchaProducer = null; 
    
    @Autowired  
    public void setCaptchaProducer(Producer captchaProducer) {  
        this.captchaProducer = captchaProducer;  
    }
    
    @RequestMapping("captcha-image.do")  
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {  
        // 禁止服务器端缓存  
        response.setDateHeader("Expires", 0);
        // 设置标准的 HTTP/1.1 no-cache headers.  
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
        // 设置IE扩展 HTTP/1.1 no-cache headers (use addHeader).  
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // 设置标准 HTTP/1.0 不缓存图片  
        response.setHeader("Pragma", "no-cache");
        //返回一个 jpeg 图片,默认是text/html(输出文档的MIMI类型)  
        response.setContentType("image/jpeg");
        //为图片创建文本  
        String capText = captchaProducer.createText();
        // 将文本保存在session中,这里就使用包中的静态变量吧  
        request.getSession().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();  
        }  
  
        System.out.println("Session 验证码是:" + request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY));  
        return null;  
    }  
    
    @RequestMapping("checkCode.do")  
    @ResponseBody
    public String checkCode(HttpServletRequest request)  {  
        //获取用户输入的验证码  
        /*String submitCode = WebUtils.getCleanParam(request,"j_code"); */ 
          
        //从session中获取系统生成的验证码  
        String kaptchaCode = request.getParameter("kaptchaCode");
        String kaptchaExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);   
          
        System.out.println("用户输入的验证码是:"+kaptchaCode+",系统生成的验证码:"+kaptchaExpected);  
        //进行比较  
        if(!kaptchaCode.isEmpty() && kaptchaCode.equalsIgnoreCase(kaptchaExpected)){  
            return "true";
        }else {  
            return "false";  
        }  
        
    }


    
}  

3.jsp页面index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.8.3.js" ></script> 
<script type="text/javascript">  
         $(function(){  //生成验证码           
            $('#kaptchaImage').click(function () {    
                $(this).hide().attr('src', 'captcha-image.do?' + Math.floor(Math.random()*100) ).fadeIn(); 
            });        
         
            $('#submitBtn').click(function(){  
                $.post('checkCode.do?kaptchaCode='+$('#kaptchaCode').val(),function(data){  
                    if (data=='true'){  
                        window.location.href="captchaSuccess.jsp";
                    }else{  
                        alert("验证码错误!");      
                        return false;  
                    }  
                });  
            });  
        });    
        window.onbeforeunload = function(){    
            //关闭窗口时自动退出    
            if(event.clientX>360&&event.clientY<0||event.altKey){       
                alert(parent.document.location);    
            }    
        };          
        function changeCode() {  //刷新  
            $('#kaptchaImage').hide().attr('src', 'captcha-image.do?' + Math.floor(Math.random()*100) ).fadeIn();    
            event.cancelBubble=true;    
        } 
        
</script>
</head>
    <body>
            <table> 
                <tr>  
                    <td>验证码:<input type="text" name="kaptchaCode" id="kaptchaCode" value="" /></td>  
                    <td align="right">
                        <img src="captcha-image.do" height="25px" width="100px" id="kaptchaImage"/> 
                        <a href="#" onclick="changeCode()">看不清?换一张</a>   
                        <input type="button" value="验证" id="submitBtn"/>
                    </td>
                </tr>  
            </table>
    </body>
</html>

4.页面效果

5.相关jar

kaptcha-2.3.2.jar

原文地址:https://www.cnblogs.com/shenqz/p/7648869.html