SpringMVC验证码生成,点击刷新及验证--基于kaptcha

直接看结果

实验结果

SpringMVC验证码生成,点击刷新及验证--基于kaptcha_第1张图片

输入正确的验证码

SpringMVC验证码生成,点击刷新及验证--基于kaptcha_第2张图片

输入错误的验证码

SpringMVC验证码生成,点击刷新及验证--基于kaptcha_第3张图片
验证码错误后自动刷新

除了数字,验证码的内容可以是多种多样的
下面看一下,数字,字母和中文混合的验证码

SpringMVC验证码生成,点击刷新及验证--基于kaptcha_第4张图片

还有其他的设置会在后面讲解

这个验证码不是我写的,是用google的kaptcha实现的,所以首先需要引入kaptcha的jar包

配置bean

其次在springmvc的配置文件配置一个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">no</prop>
                        <!-- 图片宽度 -->
                        <prop key="kaptcha.image.width">100</prop>
                        <!-- 图片高度 -->
                        <prop key="kaptcha.image.height">45</prop>
                        <!-- 验证码的字符 -->
                        <prop key="kaptcha.textproducer.char.string">0123456789abcdefghijklmnopqrstuvwxyz快过年了我想回家</prop>
                        <!-- 验证码字体颜色 -->
                        <prop key="kaptcha.textproducer.font.color">0,0,255</prop>
                        <!-- 验证码的效果,水纹 -->
                        <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.WaterRipple</prop>
                        <!-- 验证码字体大小 -->
                        <prop key="kaptcha.textproducer.font.size">38</prop>
                        <prop key="kaptcha.session.key">code</prop>
                        <!-- 验证码字数 -->
                        <prop key="kaptcha.textproducer.char.length">4</prop>
                        <!-- 验证码文字间距 -->
                        <prop key="kaptcha.textproducer.char.space">2</prop>
                        <!-- 验证码字体 -->
                        <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>
                        <!-- 不加噪声 -->
                        <prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.NoNoise</prop>
                    </props>
                </constructor-arg>
            </bean>
        </property>
    </bean>

验证码可以设置,基本的用法都进行了注释,可以根据自己的需求进行修改

开发Controller

package com.wechat.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

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.apache.commons.lang.StringUtils;
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 com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

@Controller
@RequestMapping(value = "/captcha")
public class CaptchaController {
    @Autowired
    private Producer captchaProducer;

    /** * 返回验证码的图片流 * * @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 {
        //时间戳目前并没有用到,主要是在无状态的情况下,通过一个id来识别验证码,到时候可以用uuid
        if (StringUtils.isEmpty(timestamp)) {
            System.out.println("没有时间戳\ttimestamp:" + timestamp);
            model.addAttribute("timestamp", System.currentTimeMillis());
        } else {
            System.out.println("有时间戳\ttimestamp:" + timestamp);
            model.addAttribute("timestamp", timestamp);
        }
        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;
    }

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

    /** * 检测验证码是否输入正确 * @param session * @param model * @param timestamp * @param code * @return */
    @RequestMapping(value = "/checkCaptcha", method = RequestMethod.POST)
    @ResponseBody
    public String checkCaptcha(HttpSession session, Model model,
            @RequestParam(value = "timestamp", required = false) String timestamp,
            @RequestParam(value = "code", required = false) String code) {
        boolean returnStr = false;
        System.out.println("timestamp = " + timestamp);
        System.out.println("code = " + code);
        String original = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        System.out.println("original = " + original);
        if (StringUtils.isNotEmpty(code)) {
            if (code.equalsIgnoreCase(original)) {
                returnStr = true;
            }
        }
        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"); /* alert(url); 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>

项目下载地址

https://github.com/peer44/testwechat

项目比较杂,是平时写着玩的一些示例

参考文献

http://stone02111.iteye.com/blog/1688195
http://www.aliog.com/19828.html

你可能感兴趣的:(验证码,kaptcha)