google kaptcha验证码生成器

2018-03-24 15:23:55
883次阅读
0个评论
google captcha 是google生成验证码的一个工具类,其原理是将随机生成字符串保存到session中,同时以图片的形式返回给页面,之后前台页面提交到后台进行对比。

前端代码:


<div>
 <input type="text"  id="captchaCode" name="captchaCode" placeholder="请输入验证码" autocomplete="off">
<img id="changeCaptcha" src="/getCaptchaCode"> 
</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;
    }
收藏00

登录 后评论。没有帐号? 注册 一个。