使用谷歌的kaptcha进行验证码验证

使用谷歌的kaptcha进行验证码验证


我的实现思路
1. jsp页面发出请求到Controller
1. Controller层接收请求去寻找对应的验证码视图
1. 验证码视图层生成验证码
1. 返会给jsp页面进行验证码显示
具体实现

引入jar包
        
        <dependency>
            <groupId>com.google.codegroupId>
            <artifactId>kaptchaartifactId>
            <version>${kaptcha.version}version>
        dependency>
        
jsp页面
type="text" placeholder="请输入验证码" value="" id="inputCode" />
    "${pageurl }/identify/getImageCode" id="reflush"
        οnclick="$('#reflush').attr('src','/identify/getImageCode');" />
验证码刷新js
$(function(){
    //验证码的验证
    $("#inputCode").blur(function(){
        var $value=$(this).val();
        if ($value=="") {
            alert("验证码不能为空");
        }else{
            $.post("/identify/codeIsTrue",{"inputCode":$value},function(data){
                alert(data.result);
            },"json");
        }
        $('#reflush').attr('src','/identify/getImageCode');
    });
});
Controller层
package com.education.project.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Constants;
@Controller
@RequestMapping("/identify")
public class IdentityCodeController {
    @RequestMapping("/code")
    public String code(){
        return "/code/index";
    }
    @RequestMapping("/getImageCode")
    public String createCode(){
        return "kaptchaImageCodeView";
    }
    @RequestMapping(value="/codeIsTrue", method=RequestMethod.POST)
    public @ResponseBody Map codeIsTrue(String inputCode,HttpSession session){
        Map map=new HashMap<>();
        if (inputCode.equals(session.getAttribute(Constants.KAPTCHA_SESSION_KEY))) {
            map.put("result", "验证成功");
        }else{
            map.put("result", "验证失败,你输入的验证码为:"+inputCode+",正确的验证码为:"+session.getAttribute(Constants.KAPTCHA_SESSION_KEY));
        }
        return map;
    }
}
验证码的视图层(自定义视图解析器)view.xml
id="kaptchaImageCodeView" class="com.education.project.web.view.KaptchaImageCodeView"
        p:captchaProducer-ref="captchaProducer"/>
验证码的实现类(继承springmvc的AbstractView)
package com.education.project.web.view;

import java.awt.image.BufferedImage;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.AbstractView;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

public class KaptchaImageCodeView extends AbstractView {
    private Producer captchaProducer = null;

    public void setCaptchaProducer(Producer captchaProducer) {
            this.captchaProducer = captchaProducer;
    }

    @Override
    protected void renderMergedOutputModel(Map model, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        // Set to expire far in the past.
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");

        // return a jpeg
        response.setContentType("image/jpeg");

        // create the text for the image
        String capText = captchaProducer.createText();

        // store the text in the session
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

        // create the image with the text
        BufferedImage bi = captchaProducer.createImage(capText);

        ServletOutputStream out = response.getOutputStream();

        // write the data out
        ImageIO.write(bi, "jpg", out);

        out.flush();

        out.close();
    }

}
在springmvc的配置文件中集成自定义视图
class="org.springframework.web.servlet.view.XmlViewResolver"
        p:order="10"
        p:location="classpath:views.xml"/>
验证码样式配置(具体配置参照以下文档)
<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
        <property name="config">
            <bean class="com.google.code.kaptcha.util.Config">
                <constructor-arg type="java.util.Properties">
                    <props>
                        <prop key="kaptcha.border">noprop>
                        <prop key="kaptcha.border.color">105,179,90prop>
                        <prop key="kaptcha.image.width">160prop>
                        <prop key="kaptcha.image.height">50prop>
                        <prop key="kaptcha.session.key">codeprop>
                        <prop key="kaptcha.textproducer.font.color">redprop>
                        <prop key="kaptcha.textproducer.font.size">35prop>
                        <prop key="kaptcha.textproducer.char.space">3prop>
                        <prop key="kaptcha.textproducer.char.length">5prop>
                         
                        <prop key="kaptcha.textproducer.font.names">彩云,宋体,楷体,微软雅黑prop>
                        <prop key="kaptcha.background.clear.from">whiteprop>
                        <prop key="kaptcha.background.clear.to">blackprop>

                    props>
                constructor-arg>
            bean>
        property>
配置文档

使用谷歌的kaptcha进行验证码验证_第1张图片

结果展示

这里写图片描述

你可能感兴趣的:(谷歌插件)