Jim Blog I've been trying so hard,but doesn't even matter
博客信息

geetset验证码平台

发布时间:『 2018-06-18 20:38 』  博客类别:JavaWeb  阅读(111) 评论(0)

最近在做一个校园电商系统,由于打算认真做一下所有不打算使用一般的验证码工具类直接生成图片验证码,而是使用滑动验证这种更具体验的验证方式。

虽然网上有很多验证码平台,但大多数都是试用几天,能让人免费一直用的目前只看到geetest验证,当然,能免费用的是最基础版的验证而且只能创建两个。基础版的验证方式也是十分有限的。

geetest验证的使用也很简单,官网注册后进入后台,在行为验证里点击概览,然后新建验证即可(我已经创建了两个验证,但由于涉及idkey,为了私密所以截断了)。

image.png

然后进入安装指引,行为验证

image.png

官方就有很多指导文档甚至视频解说(虽然我没看过),我个人喜欢看下文档然后直接部署项目断点运行。在部署文档里选择语言然后下载对应sdk,解压后导入到eclipse或其他IDE

我当初下载是有两种demo,自行决定需要哪种。四个类中必须更改的只有GeetestConfig.java中的geetest_idgeetest_key,换成上面图片中geetest后台的值。

配置一下StartCaptchaServlet.java,这是初始化验证的类,web.xml配置:

<servlet>
        <servlet-name>StartCaptchaServlet</servlet-name>
        <servlet-class>site.jimblog.geetest.StartCaptchaServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>StartCaptchaServlet</servlet-name>
        <url-pattern>/gt/register</url-pattern>
    </servlet-mapping>

自行封装VerifyLoginServlet.java中的逻辑,一般而言会采用aop切到需要验证的地方,或许直接在业务代码前验证?(极不推荐),通过json返回是否验证成功。贴一下这代码,非常简单:

public class VerifyLoginServlet extends HttpServlet {
               protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
               
                              GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(), 
                                                            GeetestConfig.isnewfailback());                
                              String challenge = request.getParameter(GeetestLib.fn_geetest_challenge);
                              String validate = request.getParameter(GeetestLib.fn_geetest_validate);
                              String seccode = request.getParameter(GeetestLib.fn_geetest_seccode);
                              
                              //从session中获取gt-server状态
                              int gt_server_status_code = (Integer) request.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);
                              
                              //从session中获取userid
                              String userid = (String)request.getSession().getAttribute("userid");
                              
                              //自定义参数,可选择添加
                              HashMap<String, String> param = new HashMap<String, String>(); 
                              param.put("user_id", userid); //网站用户id
                              param.put("client_type", "web"); //web:电脑上的浏览器;h5:手机上的浏览器,包括移动应用内完全内置的web_view;native:通过原生SDK植入APP应用的方式
                              param.put("ip_address", "127.0.0.1"); //传输用户请求验证时所携带的IP
                              
                              int gtResult = 0;
 
                              if (gt_server_status_code == 1) {
                                             //gt-server正常,向gt-server进行二次验证     
                                             gtResult = gtSdk.enhencedValidateRequest(challenge, validate, seccode, param);
                                             System.out.println(gtResult);
                              } else {
                                             // gt-server非正常情况下,进行failback模式验证        
                                             System.out.println("failback:use your own server captcha validate");
                                             gtResult = gtSdk.failbackValidateRequest(challenge, validate, seccode);
                                             System.out.println(gtResult);
                              }
 
                              if (gtResult == 1) {
                                             // 验证成功
                                             PrintWriter out = response.getWriter();
                                             JSONObject data = new JSONObject();
                                             try {
                                                            data.put("status", "success");
                                                            data.put("version", gtSdk.getVersionInfo());
                                             } catch (JSONException e) {
                                                            e.printStackTrace();
                                             }
                                             out.println(data.toString());
                              }
                              else {
                                             // 验证失败
                                             JSONObject data = new JSONObject();
                                             try {
                                                            data.put("status", "fail");
                                                            data.put("version", gtSdk.getVersionInfo());
                                             } catch (JSONException e) {
                                                            e.printStackTrace();
                                             }
                                             PrintWriter out = response.getWriter();
                                             out.println(data.toString());
                              }
               }
}

我个人的封装思路是写成一个返回boolean值的方法,传入request和map(业务代码是通过@ResponseBody封装map返回json),验证代码不变,把本该封装在json里的放到map里,验证正确返回true,不然返回false。


然后是前端代码,注意引用gt.jsjquery,页面只需提取验证相关的即可:

<div>
        <label>完成验证:</label>
        <div id="captcha">
            <p id="wait">正在加载验证码......</p>
        </div>
    </div>
    <br>
<p id="notice1">请先完成验证</p>

然后是ajax提交数据,前面的表单数据提交根据个人需要改变,后面的验证初始化ajax如果更改了上面的初始化servlet的配置,则定位到自己定义的url,产品形式和宽度可以自定义,其他都不用改:

<script>
    var handler = function (captchaObj) {
        $("#submit").click(function (e) {
            var result = captchaObj.getValidate();
            if (!result) {
                $("#notice").show();
                setTimeout(function () {
                    $("#notice").hide();
                }, 2000);
            } else {
                $.ajax({
                    url: '表单数据提交地址‘,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        username: $('#username').val(),
                        password: $('#password').val(),
                        geetest_challenge: result.geetest_challenge,
                        geetest_validate: result.geetest_validate,
                        geetest_seccode: result.geetest_seccode
                    },
                    success: function (data) {
                        if (data.status === 'success') {
                            alert('登录成功');
                        } else if (data.status === 'fail') {
                            alert('登录失败');
                        }
                    }
                })
            }
            e.preventDefault();
        });
        // 将验证码加到id为captcha的元素里,同时会有三个input的值用于表单提交
        captchaObj.appendTo("#captcha");
        captchaObj.onReady(function () {
            $("#wait").hide();
        });
        // 更多接口参考:http://www.geetest.com/install/sections/idx-client-sdk.html
    };
    $.ajax({
        url: "gt/register?t=" + (new Date()).getTime(), // 加随机数防止缓存
        type: "get",
        dataType: "json",
        success: function (data) {
            // 调用 initGeetest 初始化参数
            // 参数1:配置参数
            // 参数2:回调,回调的第一个参数验证码对象,之后可以使用它调用相应的接口
            initGeetest({
                gt: data.gt,
                challenge: data.challenge,
                new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机
                offline: !data.success, // 表示用户后台检测极验服务器是否宕机,一般不需要关注
                product: "popup", // 产品形式,包括:float,popup
                width: "100%"
                // 更多配置参数请参见:http://www.geetest.com/install/sections/idx-client-sdk.html#config
            }, handler);
        }
    });
</script>

大致上就是如此,然后就是装逼的滑动验证了。


关键字:   geetest     验证码  
博主信息
Jim
(生命,是一场徒劳的坚持)