关闭

springMVC中验证码生成工具kaptcha的使用

标签: kaptcha
202人阅读 评论(0) 收藏 举报
分类:

kaptcha的使用比较方便的生成验证码的工具包,只需添加jar包依赖之后简单地配置就可以使用了。

第一步:下载jar包:kaptcha-2.3.jar

        第二步:在springmvc的配置文件配置一个bean

      

<!-- 验证码 -->
<span style="white-space:pre">	</span> <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
<span style="white-space:pre">		</span>  <property name="config">
<span style="white-space:pre">		</span>          <bean class="com.google.code.kaptcha.util.Config">
<span style="white-space:pre">				</span>  <!--通过构造函数注入属性值 -->
<span style="white-space:pre">		</span>            <constructor-arg type="java.util.Properties">
<span style="white-space:pre">					</span><props>
<span style="white-space:pre">						</span><!-- 图片边框,合法值:yes , no -->
<span style="white-space:pre">						</span><prop key="kaptcha.border">yes</prop>
<span style="white-space:pre">						</span><!-- 边框颜色,合法值: r,g,b (and optional alpha) 或者white,black,blue -->
<span style="white-space:pre">						</span><prop key="kaptcha.border.color">black</prop>
<span style="white-space:pre">						</span><!-- 边框厚度,合法值:>0 -->
<span style="white-space:pre">						</span><prop key="kaptcha.border.thickness">1</prop>
<span style="white-space:pre">						</span><!-- 图片宽 150 -->
<span style="white-space:pre">						</span><prop key="kaptcha.image.width">200</prop>
<span style="white-space:pre">						</span><!-- 图片高 42-->
<span style="white-space:pre">						</span><prop key="kaptcha.image.height">42</prop>
<span style="white-space:pre">						</span><!-- 图片实现类 -->
<span style="white-space:pre">						</span><prop key="kaptcha.producer.impl">com.google.code.kaptcha.impl.DefaultKaptcha</prop>
<span style="white-space:pre">						</span><!-- 文本实现类 -->
<span style="white-space:pre">						</span><prop key="kaptcha.textproducer.impl">com.google.code.kaptcha.text.impl.DefaultTextCreator</prop>
<span style="white-space:pre">						</span><!-- 文本集合,验证码值从此集合中获取 -->
<span style="white-space:pre">						</span><prop key="kaptcha.textproducer.char.string">1234567890qwertyuioplkjhgfdsazxcvbnm</prop>
<span style="white-space:pre">						</span><!-- 验证码长度4-->
<span style="white-space:pre">						</span><prop key="kaptcha.textproducer.char.length">4</prop>
<span style="white-space:pre">						</span><!-- 字体 Arial, Courie-->
<span style="white-space:pre">						</span><prop key="kaptcha.textproducer.font.names">Arial, Courier</prop>
<span style="white-space:pre">						</span><!-- 字体大小 40px-->
<span style="white-space:pre">						</span><prop key="kaptcha.textproducer.font.size">30</prop>
<span style="white-space:pre">						</span><!-- 字体颜色,合法值: r,g,b 或者 white,black,blue-->
<span style="white-space:pre">						</span><prop key="kaptcha.textproducer.font.color">black</prop>
<span style="white-space:pre">						</span><!-- 文字间隔 2 -->
<span style="white-space:pre">						</span><prop key="kaptcha.textproducer.char.space">2</prop>
<span style="white-space:pre">						</span><!-- 干扰实现类 -->
<span style="white-space:pre">						</span><prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.DefaultNoise</prop>
<span style="white-space:pre">						</span><!-- 干扰颜色,合法值: r,g,b 或者 white,black,blue.-->
<span style="white-space:pre">						</span><prop key="kaptcha.noise.color">black</prop>
<span style="white-space:pre">						</span><!-- 图片样式: 水纹com.google.code.kaptcha.impl.WaterRipple
<span style="white-space:pre">							</span>鱼眼com.google.code.kaptcha.impl.FishEyeGimpy
<span style="white-space:pre">							</span>阴影com.google.code.kaptcha.impl.ShadowGimpy-->
<span style="white-space:pre">						</span><prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.FishEyeGimpy</prop>
<span style="white-space:pre">						</span><!-- 背景实现类 -->
<span style="white-space:pre">						</span><prop key="kaptcha.background.impl">com.google.code.kaptcha.impl.DefaultBackground</prop>
<span style="white-space:pre">						</span><!-- 背景颜色渐变,开始颜色-->
<span style="white-space:pre">						</span><prop key="kaptcha.background.clear.to">white</prop>
<span style="white-space:pre">						</span><!-- 文字渲染器< -->
<span style="white-space:pre">						</span><prop key="kaptcha.word.impl">com.google.code.kaptcha.text.impl.DefaultWordRenderer</prop>
<span style="white-space:pre">						</span><!-- session中存放验证码的key键 -->
<span style="white-space:pre">						</span><prop key="kaptcha.session.key">KAPTCHA_SESSION_KEY</prop>
<span style="white-space:pre">						</span><prop key="kaptcha.session.date">KAPTCHA_SESSION_DATE</prop><span style="white-space:pre">						</span>
<span style="white-space:pre">					</span></props>
<span style="white-space:pre">				</span></constructor-arg>
<span style="white-space:pre">			</span></bean>
<span style="white-space:pre">		</span></property>
<span style="white-space:pre">	</span></bean>

开发controller


jsp页面

package com.wechat.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码相关的接口
 *
 * @author gaowei.cheng
 */
@Controller
@RequestMapping(value = "/captcha")
public class CaptchaController {

    private static final Log log = LogFactory.getLog(CaptchaController.class);
    @Autowired
    private Producer captchaProducer;

    /**
     * 页面入口
     * @param model
     * @return
     */
    @RequestMapping(value = "/getCaptcha", method = RequestMethod.GET)
    public String getCaptcha(Model model) {
        model.addAttribute("timestamp", System.currentTimeMillis());
        return "captcha";
    }

    /**
     * 生成带验证码的图片
     * @param model
     * @param request
     * @param response
     * @param timestamp
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/getCaptchaImage.jpg", method = RequestMethod.GET)
    public ModelAndView getCaptchaImage(Model model,HttpServletRequest request, HttpServletResponse response,
                                        @RequestParam(value = "timestamp", required = false) String timestamp) throws IOException {
        if (StringUtils.isEmpty(timestamp)) {
            //System.out.println("没有时间戳\ttimestamp:" + timestamp);
            model.addAttribute("timestamp", System.currentTimeMillis());
        } else {
            //System.out.println("有时间戳\ttimestamp:" + timestamp);
            model.addAttribute("timestamp", timestamp);
        }

        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();

        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        log.info("======生成了一个验证码,内容为:" + capText);
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }

    /**
     *
     * @param timestamp
     * @param code
     * @param request
     * @return true或fasle,ture表示验证成功,false表示验证失败
     */
    @RequestMapping(value = "/checkCaptcha", method = RequestMethod.POST)
    @ResponseBody
    public String checkCaptcha(@RequestParam(value = "timestamp", required = false) String timestamp, @RequestParam(value = "code", required = false) String code,HttpServletRequest request) {
        boolean returnStr = false;

        String original =(String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        log.info("======用户输入的验证码:" + code);
        log.info("======正确的验证码:" + original);

        if (StringUtils.isNotEmpty(code)) {
            if (code.equalsIgnoreCase(original)) {
                returnStr = true;
            }
        }

        log.info("======验证结果" + returnStr);
        return returnStr + "";

    }
}

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>验证码</title>
<c:catch var="importError0">
    <c:import url="common/base.jsp" charEncoding="utf-8"></c:import>
</c:catch>
<c:out value="${importError0}"></c:out>
</head>
<body>
    <img id="imgObj" alt="验证码"
        src="${base }/captcha/getCaptchaImage.jpg"
        onclick="changeImg()">
    <form action="" id="loginform">
        请输入验证码:<input id="imageContent" name="imageContent" type="text"><br>
        <input id="timestamp" name="timestamp" value="${timestamp }" type="hidden" >
        <button>提交</button>
    </form>
</body>
<script type="text/javascript">
    var base = "${base}";
    function checkImageCode(code) {
        var timestamp = $("#timestamp").val().trim();
        console.log(code + " " + timestamp);
        var haha = "";

        $.ajax({
            type : 'post',
            async : false,
            url : base+'/captcha/checkCaptcha',
            data : {
                "code" : code
            },
            success : function(data) {
                haha = data;
            }
        });
        console.log(haha);
        return haha;
    }
    $("form").submit(function check(){
        var code = $("#imageContent").val().trim();
        if(code.length != 0 ){
            var status = checkImageCode(code).trim();
            //alert(status);
            if(status.indexOf("true")>=0){
                alert("成功");
            }else{
                changeImg();
                alert("失败");
            }
        }else{
            alert("请输入验证码");
        }

        return false;
        });
    function changeImg() {
        var imgSrc = $("#imgObj");
        var src = imgSrc.attr("src");
        imgSrc.attr("src", chgUrl(src));
    };
    //时间戳   
    //为了使每次生成图片不一致,即不让浏览器读缓存,所以需要加上时间戳   
    function chgUrl(url) {
        var timestamp = (new Date()).valueOf();
        var stamp = $("#timestamp");
        url = url.substring(0, 60);
        if ((url.indexOf("&") >= 0)) {
            url = url + "×tamp=" + timestamp;
        } else {
            url = url + "?timestamp=" + timestamp;
            stamp.val(timestamp);
        } 
        return url;
    };
</script>
</html>


我自己在测试的时候验证码一直出不来,最后发现是因为设置了拦截器的问题,需要修改拦截器的设置。

我的拦截器一开始设置的/**后来改为/controller/*没问题了

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:14579次
    • 积分:491
    • 等级:
    • 排名:千里之外
    • 原创:30篇
    • 转载:39篇
    • 译文:0篇
    • 评论:3条
    最新评论