验证码生成器google kaptcha

WEB前端 waitig 666℃ 百度已收录 0评论

google captcha 是google生成验证码的一个工具类,其原理是将随机生成字符串保存到session中,同时以图片的形式返回给页面,之后前台页面提交到后台进行对比。

前端代码:

 <div class="ui-col-75">
 <input type="text" class="ui-input-control ui-col-60" id="captchaCode" name="captchaCode" placeholder="请输入验证码" autocomplete="off">
<img id="changeCaptcha" class="change-capt-cha" src="${regUrlBase}/common/getCaptchaCode"> 
<div href="javascript:;" class="change-capt-cha reg-capt-img"><i class="icon-gantanhao-yuankuang"></i>看不清?换一张</div>
</div>

后端代码:

@RequestMapping("getCaptchaCode")
    public void getCaptchaCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        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);
        // 利用生成的字符串构建图片
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        }
        finally {
            out.close();
        }
    }

验证码校验:

@RequestMapping("checkCaptchaCode")
    @ResponseBody
    public boolean checkCaptchaCode(HttpServletRequest request, @RequestParam("captchaCode") String captchaCode) throws IOException {
        return vaildCode(request, captchaCode);
    }

public boolean vaildCode(HttpServletRequest request,String captchaCode) {
        // 用户输入的验证码的值
        String kaptchaExpected = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        // 校验验证码是否正确
        if (captchaCode == null || !captchaCode.equals(kaptchaExpected)) {
            return false;// 返回验证码错误
        }
        return true;
    }

本文由【waitig】发表在等英博客
本文固定链接:验证码生成器google kaptcha
欢迎关注本站官方公众号,每日都有干货分享!
等英博客官方公众号
点赞 (0)分享 (0)