极验验证码使用


一、去极验注册账号获得ID和key

地址:https://account.geetest.com/


二、导入sdk架包

需要两个架包:java-json.jar  和  servlet-api.jar

下载地址:http://download.csdn.net/download/junmoxi/9949773


三、编写后台代码

StartCaptchaServlet.java  (获得验证码)

[java]  view plain  copy
  1. <span style="font-size:18px;">package com.lei.servlet;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import com.lei.config.GeetestConfig;  
  12. import com.lei.sdk.GeetestLib;  
  13.   
  14.   
  15. public class StartCaptchaServlet extends HttpServlet {  
  16.     protected void doGet(HttpServletRequest request,  
  17.             HttpServletResponse response) throws ServletException, IOException {  
  18.         GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(), GeetestConfig.isnewfailback());  
  19.         String resStr = "{}";  
  20.           
  21.         //自定义userid  
  22.         String userid = "test";  
  23.         //进行验证预处理  
  24.         int gtServerStatus = gtSdk.preProcess(userid);  
  25.           
  26.         //将服务器状态设置到session中  
  27.         request.getSession().setAttribute(gtSdk.gtServerStatusSessionKey, gtServerStatus);  
  28.         //将userid设置到session中  
  29.         request.getSession().setAttribute("userid", userid);  
  30.           
  31.         resStr = gtSdk.getResponseStr();  
  32.         PrintWriter out = response.getWriter();  
  33.         out.println(resStr);  
  34.     }  
  35. }</span>  
VerifyLoginServlet.java  (验证验证码)


[java]  view plain  copy
  1. <span style="font-size:18px;">package com.lei.servlet;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import org.json.JSONException;  
  12. import org.json.JSONObject;  
  13.   
  14. import com.lei.config.GeetestConfig;  
  15. import com.lei.sdk.GeetestLib;  
  16.   
  17.   
  18.   
  19. /** 
  20.  * 使用post方式,返回验证结果, request表单中必须包含challenge, validate, seccode 
  21.  */  
  22. public class VerifyLoginServlet extends HttpServlet {  
  23.   
  24.     protected void doPost(HttpServletRequest request,  
  25.             HttpServletResponse response) throws ServletException, IOException {  
  26.   
  27.         GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(),   
  28.                 GeetestConfig.isnewfailback());  
  29.               
  30.         String challenge = request.getParameter(GeetestLib.fn_geetest_challenge);  
  31.         String validate = request.getParameter(GeetestLib.fn_geetest_validate);  
  32.         String seccode = request.getParameter(GeetestLib.fn_geetest_seccode);  
  33.           
  34.         //从session中获取gt-server状态  
  35.         int gt_server_status_code = (Integer) request.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);  
  36.           
  37.         //从session中获取userid  
  38.         String userid = (String)request.getSession().getAttribute("userid");  
  39.           
  40.         int gtResult = 0;  
  41.   
  42.         if (gt_server_status_code == 1) {  
  43.             //gt-server正常,向gt-server进行二次验证  
  44.                   
  45.             gtResult = gtSdk.enhencedValidateRequest(challenge, validate, seccode, userid);  
  46.             System.out.println(gtResult);  
  47.         } else {  
  48.             // gt-server非正常情况下,进行failback模式验证  
  49.                   
  50.             System.out.println("failback:use your own server captcha validate");  
  51.             gtResult = gtSdk.failbackValidateRequest(challenge, validate, seccode);  
  52.             System.out.println(gtResult);  
  53.         }  
  54.   
  55.   
  56.         if (gtResult == 1) {  
  57.             // 验证成功  
  58.             PrintWriter out = response.getWriter();  
  59.             JSONObject data = new JSONObject();  
  60.             try {  
  61.                 data.put("status""success");  
  62.                 data.put("version", gtSdk.getVersionInfo());  
  63.             } catch (JSONException e) {  
  64.                 e.printStackTrace();  
  65.             }  
  66.             out.println(data.toString());  
  67.         }  
  68.         else {  
  69.             // 验证失败  
  70.             JSONObject data = new JSONObject();  
  71.             try {  
  72.                 data.put("status""fail");  
  73.                 data.put("version", gtSdk.getVersionInfo());  
  74.             } catch (JSONException e) {  
  75.                 e.printStackTrace();  
  76.             }  
  77.             PrintWriter out = response.getWriter();  
  78.             out.println(data.toString());  
  79.         }  
  80.   
  81.     }  
  82. }  
  83. </span>  

GeetestConfig.java  (配置文件)

[java]  view plain  copy
  1. <span style="font-size:18px;">package com.lei.config;  
  2.   
  3. import javax.swing.text.StyledEditorKit.BoldAction;  
  4.   
  5. /** 
  6.  * GeetestWeb配置文件 
  7.  *  
  8.  * 
  9.  */  
  10. public class GeetestConfig {  
  11.   
  12.     // 填入自己的captcha_id和private_key  
  13.     private static final String geetest_id = "7e5a9550b98e8496127526b0459d260d";  
  14.     private static final String geetest_key = "354c66612d75838bfebc54f2c9c8d271";  
  15.     private static final boolean newfailback = true;  
  16.   
  17.     public static final String getGeetest_id() {  
  18.         return geetest_id;  
  19.     }  
  20.   
  21.     public static final String getGeetest_key() {  
  22.         return geetest_key;  
  23.     }  
  24.       
  25.     public static final boolean isnewfailback() {  
  26.         return newfailback;  
  27.     }  
  28.   
  29. }  
  30. </span>  

GeetestLib.java  (SDK)


[java]  view plain  copy
  1. <span style="font-size:18px;">package com.lei.sdk;  
  2.   
  3. import java.awt.print.Printable;  
  4. import java.io.BufferedReader;  
  5. import java.io.BufferedWriter;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.InputStreamReader;  
  9. import java.io.OutputStreamWriter;  
  10. import java.lang.reflect.GenericArrayType;  
  11. import java.net.HttpURLConnection;  
  12. import java.net.InetAddress;  
  13. import java.net.Socket;  
  14. import java.net.URL;  
  15. import java.security.MessageDigest;  
  16. import java.security.NoSuchAlgorithmException;  
  17. import java.text.SimpleDateFormat;  
  18. import java.util.ArrayList;  
  19. import java.util.HashMap;  
  20. import java.util.logging.Logger;  
  21.   
  22. import javax.print.DocFlavor.STRING;  
  23. import javax.servlet.descriptor.JspConfigDescriptor;  
  24. import javax.servlet.http.HttpServletRequest;  
  25.   
  26. import org.json.JSONException;  
  27. import org.json.JSONObject;  
  28.   
  29. /** 
  30.  * Java SDK 
  31.  *  
  32.  */  
  33. public class GeetestLib {  
  34.   
  35.     protected final String verName = "4.0";  
  36.     protected final String sdkLang = "java";  
  37.   
  38.     protected final String apiUrl = "http://api.geetest.com";   
  39.       
  40.     protected final String registerUrl = "/register.php";   
  41.     protected final String validateUrl = "/validate.php";  
  42.       
  43.     protected final String json_format = "1";  
  44.        
  45.     /** 
  46.      * 极验验证二次验证表单数据 chllenge 
  47.      */  
  48.     public static final String fn_geetest_challenge = "geetest_challenge";  
  49.       
  50.     /** 
  51.      * 极验验证二次验证表单数据 validate 
  52.      */  
  53.     public static final String fn_geetest_validate = "geetest_validate";  
  54.       
  55.     /** 
  56.      * 极验验证二次验证表单数据 seccode 
  57.      */  
  58.     public static final String fn_geetest_seccode = "geetest_seccode";  
  59.   
  60.     /** 
  61.      * 公钥 
  62.      */  
  63.     private String captchaId = "";  
  64.   
  65.     /** 
  66.      * 私钥 
  67.      */  
  68.     private String privateKey = "";  
  69.       
  70.     /** 
  71.      * 是否开启新的failback 
  72.      */  
  73.     private boolean newFailback = false;  
  74.       
  75.     /** 
  76.      * 返回字符串 
  77.      */  
  78.     private String responseStr = "";  
  79.       
  80.     /** 
  81.      * 调试开关,是否输出调试日志 
  82.      */  
  83.     public boolean debugCode = true;  
  84.       
  85.     /** 
  86.      * 极验验证API服务状态Session Key 
  87.      */  
  88.     public String gtServerStatusSessionKey = "gt_server_status";  
  89.       
  90.     /** 
  91.      * 标记字段 
  92.      */  
  93.     public String userId = "";  
  94.       
  95.     /** 
  96.      * 标记验证模块所应用的终端类型 
  97.      */  
  98.     public String clientType = "";  
  99.       
  100.     /** 
  101.      * 标记用户请求验证时所携带的IP 
  102.      */  
  103.     public String ipAddress  = "";  
  104.       
  105.       
  106.     /** 
  107.      * 带参数构造函数 
  108.      *  
  109.      * @param captchaId 
  110.      * @param privateKey 
  111.      */  
  112.     public GeetestLib(String captchaId, String privateKey, boolean newFailback) {  
  113.           
  114.         this.captchaId = captchaId;  
  115.         this.privateKey = privateKey;  
  116.         this.newFailback = newFailback;  
  117.     }  
  118.       
  119.     /** 
  120.      * 获取本次验证初始化返回字符串 
  121.      *  
  122.      * @return 初始化结果 
  123.      */  
  124.     public String getResponseStr() {  
  125.           
  126.         return responseStr;  
  127.           
  128.     }  
  129.       
  130.     public String getVersionInfo() {  
  131.           
  132.         return verName;  
  133.           
  134.     }  
  135.   
  136.     /** 
  137.      * 预处理失败后的返回格式串 
  138.      *  
  139.      * @return 
  140.      */  
  141.     private String getFailPreProcessRes() {  
  142.   
  143.         Long rnd1 = Math.round(Math.random() * 100);  
  144.         Long rnd2 = Math.round(Math.random() * 100);  
  145.         String md5Str1 = md5Encode(rnd1 + "");  
  146.         String md5Str2 = md5Encode(rnd2 + "");  
  147.         String challenge = md5Str1 + md5Str2.substring(02);  
  148.           
  149.         JSONObject jsonObject = new JSONObject();  
  150.         try {  
  151.               
  152.             jsonObject.put("success"0);  
  153.             jsonObject.put("gt"this.captchaId);  
  154.             jsonObject.put("challenge", challenge);  
  155.             jsonObject.put("new_captcha"this.newFailback);  
  156.               
  157.         } catch (JSONException e) {  
  158.               
  159.             gtlog("json dumps error");  
  160.               
  161.         }  
  162.           
  163.         return jsonObject.toString();  
  164.           
  165.     }  
  166.   
  167.     /** 
  168.      * 预处理成功后的标准串 
  169.      *  
  170.      */  
  171.     private String getSuccessPreProcessRes(String challenge) {  
  172.           
  173.         gtlog("challenge:" + challenge);  
  174.           
  175.         JSONObject jsonObject = new JSONObject();  
  176.         try {  
  177.               
  178.             jsonObject.put("success"1);  
  179.             jsonObject.put("gt"this.captchaId);  
  180.             jsonObject.put("challenge", challenge);  
  181.               
  182.         } catch (JSONException e) {  
  183.               
  184.             gtlog("json dumps error");  
  185.               
  186.         }  
  187.           
  188.         return jsonObject.toString();  
  189.           
  190.     }  
  191.       
  192.     /** 
  193.      * 验证初始化预处理 
  194.      * 
  195.      * @return 1表示初始化成功,0表示初始化失败 
  196.      */  
  197.     public int preProcess() {  
  198.   
  199.         if (registerChallenge() != 1) {  
  200.               
  201.             this.responseStr = this.getFailPreProcessRes();  
  202.             return 0;  
  203.               
  204.         }  
  205.           
  206.         return 1;  
  207.   
  208.     }  
  209.       
  210.     /** 
  211.      * 验证初始化预处理 
  212.      * 
  213.      * @param userid 
  214.      * @return 1表示初始化成功,0表示初始化失败 
  215.      */  
  216.     public int preProcess(String userid){  
  217.           
  218.         this.userId = userid;  
  219.         return this.preProcess();  
  220.           
  221.     }     
  222.   
  223.     /** 
  224.      * 用captchaID进行注册,更新challenge 
  225.      *  
  226.      * @return 1表示注册成功,0表示注册失败 
  227.      */  
  228.     private int registerChallenge() {  
  229.           
  230.         try {  
  231.               
  232.             String getUrl = apiUrl + registerUrl + "?";  
  233.             String param = "gt=" + this.captchaId + "&json_format=" + this.json_format;  
  234.               
  235.             if (this.userId != ""){  
  236.                 param = param + "&user_id=" + this.userId;  
  237.                 this.userId = "";  
  238.             }  
  239.             if (this.clientType != ""){  
  240.                 param = param + "&client_type=" + this.clientType;  
  241.                 this.clientType = "";  
  242.             }  
  243.             if (this.ipAddress != ""){  
  244.                 param = param + "&ip_address=" + this.ipAddress;  
  245.                 this.ipAddress = "";  
  246.             }  
  247.               
  248.             gtlog("GET_URL:" + getUrl + param);  
  249.             String result_str = readContentFromGet(getUrl + param);  
  250.             if (result_str == "fail"){  
  251.                   
  252.                 gtlog("gtServer register challenge failed");  
  253.                 return 0;  
  254.                   
  255.             }  
  256.               
  257.             gtlog("result:" + result_str);  
  258.             JSONObject jsonObject = new JSONObject(result_str);  
  259.             String return_challenge = jsonObject.getString("challenge");  
  260.           
  261.             gtlog("return_challenge:" + return_challenge);  
  262.               
  263.             if (return_challenge.length() == 32) {  
  264.                   
  265.                 this.responseStr = this.getSuccessPreProcessRes(this.md5Encode(return_challenge + this.privateKey));  
  266.                   
  267.                 return 1;  
  268.                   
  269.             }  
  270.             else {  
  271.                   
  272.                 gtlog("gtServer register challenge error");  
  273.                       
  274.                 return 0;  
  275.                   
  276.             }  
  277.         } catch (Exception e) {  
  278.               
  279.             gtlog(e.toString());  
  280.             gtlog("exception:register api");  
  281.               
  282.         }  
  283.         return 0;  
  284.     }  
  285.       
  286.     /** 
  287.      * 判断一个表单对象值是否为空 
  288.      *  
  289.      * @param gtObj 
  290.      * @return 
  291.      */  
  292.     protected boolean objIsEmpty(Object gtObj) {  
  293.           
  294.         if (gtObj == null) {  
  295.               
  296.             return true;  
  297.               
  298.         }  
  299.   
  300.         if (gtObj.toString().trim().length() == 0) {  
  301.               
  302.             return true;  
  303.               
  304.         }  
  305.   
  306.         return false;  
  307.     }  
  308.   
  309.     /** 
  310.      * 检查客户端的请求是否合法,三个只要有一个为空,则判断不合法 
  311.      *  
  312.      * @param request 
  313.      * @return 
  314.      */  
  315.     private boolean resquestIsLegal(String challenge, String validate, String seccode) {  
  316.   
  317.         if (objIsEmpty(challenge)) {  
  318.               
  319.             return false;  
  320.               
  321.         }  
  322.   
  323.         if (objIsEmpty(validate)) {  
  324.               
  325.             return false;  
  326.               
  327.         }  
  328.   
  329.         if (objIsEmpty(seccode)) {  
  330.               
  331.             return false;  
  332.               
  333.         }  
  334.   
  335.         return true;  
  336.     }  
  337.       
  338.       
  339.     /** 
  340.      * 服务正常的情况下使用的验证方式,向gt-server进行二次验证,获取验证结果 
  341.      *  
  342.      * @param challenge 
  343.      * @param validate 
  344.      * @param seccode 
  345.      * @return 验证结果,1表示验证成功0表示验证失败 
  346.      */  
  347.     public int enhencedValidateRequest(String challenge, String validate, String seccode) {   
  348.           
  349.         if (!resquestIsLegal(challenge, validate, seccode)) {  
  350.               
  351.             return 0;  
  352.               
  353.         }  
  354.           
  355.         gtlog("request legitimate");  
  356.           
  357.         String postUrl = this.apiUrl + this.validateUrl;  
  358.         String param = String.format("challenge=%s&validate=%s&seccode=%s&json_format=%s",   
  359.                                      challenge, validate, seccode, this.json_format);   
  360.           
  361.         String response = "";  
  362.         try {  
  363.               
  364.             if (validate.length() <= 0) {  
  365.                   
  366.                 return 0;  
  367.                   
  368.             }  
  369.   
  370.             if (!checkResultByPrivate(challenge, validate)) {  
  371.                   
  372.                 return 0;  
  373.                   
  374.             }  
  375.               
  376.             gtlog("checkResultByPrivate");  
  377.               
  378.             response = readContentFromPost(postUrl, param);  
  379.   
  380.             gtlog("response: " + response);  
  381.               
  382.         } catch (Exception e) {  
  383.               
  384.             e.printStackTrace();  
  385.               
  386.         }  
  387.           
  388.         String return_seccode = "";  
  389.           
  390.         try {  
  391.               
  392.             JSONObject return_map = new JSONObject(response);  
  393.             return_seccode = return_map.getString("seccode");  
  394.             gtlog("md5: " + md5Encode(return_seccode));  
  395.   
  396.             if (return_seccode.equals(md5Encode(seccode))) {  
  397.                   
  398.                 return 1;  
  399.                   
  400.             } else {  
  401.                   
  402.                 return 0;  
  403.                   
  404.             }  
  405.               
  406.         } catch (JSONException e) {  
  407.               
  408.           
  409.             gtlog("json load error");  
  410.             return 0;  
  411.               
  412.         }  
  413.           
  414.     }  
  415.       
  416.     /** 
  417.      * 服务正常的情况下使用的验证方式,向gt-server进行二次验证,获取验证结果 
  418.      *  
  419.      * @param challenge 
  420.      * @param validate 
  421.      * @param seccode 
  422.      * @param userid 
  423.      * @return 验证结果,1表示验证成功0表示验证失败 
  424.      */  
  425.     public int enhencedValidateRequest(String challenge, String validate, String seccode, String userid) {    
  426.           
  427.         this.userId = userid;  
  428.         return this.enhencedValidateRequest(challenge, validate, seccode);  
  429.     }  
  430.   
  431.     /** 
  432.      * failback使用的验证方式 
  433.      *  
  434.      * @param challenge 
  435.      * @param validate 
  436.      * @param seccode 
  437.      * @return 验证结果,1表示验证成功0表示验证失败 
  438.      */  
  439.     public int failbackValidateRequest(String challenge, String validate, String seccode) {  
  440.   
  441.         gtlog("in failback validate");  
  442.   
  443.         if (!resquestIsLegal(challenge, validate, seccode)) {  
  444.             return 0;  
  445.         }  
  446.         gtlog("request legitimate");  
  447.   
  448.         return 1;  
  449.     }  
  450.   
  451.     /** 
  452.      * 输出debug信息,需要开启debugCode 
  453.      *  
  454.      * @param message 
  455.      */  
  456.     public void gtlog(String message) {  
  457.         if (debugCode) {  
  458.             System.out.println("gtlog: " + message);  
  459.         }  
  460.     }  
  461.   
  462.     protected boolean checkResultByPrivate(String challenge, String validate) {  
  463.         String encodeStr = md5Encode(privateKey + "geetest" + challenge);  
  464.         return validate.equals(encodeStr);  
  465.     }  
  466.       
  467.     /** 
  468.      * 发送GET请求,获取服务器返回结果 
  469.      *  
  470.      * @param getURL 
  471.      * @return 服务器返回结果 
  472.      * @throws IOException 
  473.      */  
  474.     private String readContentFromGet(String URL) throws IOException {  
  475.   
  476.         URL getUrl = new URL(URL);  
  477.         HttpURLConnection connection = (HttpURLConnection) getUrl  
  478.                 .openConnection();  
  479.   
  480.         connection.setConnectTimeout(2000);// 设置连接主机超时(单位:毫秒)  
  481.         connection.setReadTimeout(2000);// 设置从主机读取数据超时(单位:毫秒)  
  482.   
  483.         // 建立与服务器的连接,并未发送数据  
  484.         connection.connect();  
  485.           
  486.         if (connection.getResponseCode() == 200) {  
  487.             // 发送数据到服务器并使用Reader读取返回的数据  
  488.             StringBuffer sBuffer = new StringBuffer();  
  489.   
  490.             InputStream inStream = null;  
  491.             byte[] buf = new byte[1024];  
  492.             inStream = connection.getInputStream();  
  493.             for (int n; (n = inStream.read(buf)) != -1;) {  
  494.                 sBuffer.append(new String(buf, 0, n, "UTF-8"));  
  495.             }  
  496.             inStream.close();  
  497.             connection.disconnect();// 断开连接  
  498.               
  499.             return sBuffer.toString();    
  500.         }  
  501.         else {  
  502.               
  503.             return "fail";  
  504.         }  
  505.     }  
  506.       
  507.     /** 
  508.      * 发送POST请求,获取服务器返回结果 
  509.      *  
  510.      * @param getURL 
  511.      * @return 服务器返回结果 
  512.      * @throws IOException 
  513.      */  
  514.     private String readContentFromPost(String URL, String data) throws IOException {  
  515.           
  516.         gtlog(data);  
  517.         URL postUrl = new URL(URL);  
  518.         HttpURLConnection connection = (HttpURLConnection) postUrl  
  519.                 .openConnection();  
  520.   
  521.         connection.setConnectTimeout(2000);// 设置连接主机超时(单位:毫秒)  
  522.         connection.setReadTimeout(2000);// 设置从主机读取数据超时(单位:毫秒)  
  523.         connection.setRequestMethod("POST");  
  524.         connection.setDoInput(true);  
  525.         connection.setDoOutput(true);  
  526.         connection.setRequestProperty("Content-Type""application/x-www-form-urlencoded");  
  527.           
  528.         // 建立与服务器的连接,并未发送数据  
  529.         connection.connect();  
  530.           
  531.          OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(), "utf-8");    
  532.          outputStreamWriter.write(data);    
  533.          outputStreamWriter.flush();  
  534.          outputStreamWriter.close();  
  535.           
  536.         if (connection.getResponseCode() == 200) {  
  537.             // 发送数据到服务器并使用Reader读取返回的数据  
  538.             StringBuffer sBuffer = new StringBuffer();  
  539.   
  540.             InputStream inStream = null;  
  541.             byte[] buf = new byte[1024];  
  542.             inStream = connection.getInputStream();  
  543.             for (int n; (n = inStream.read(buf)) != -1;) {  
  544.                 sBuffer.append(new String(buf, 0, n, "UTF-8"));  
  545.             }  
  546.             inStream.close();  
  547.             connection.disconnect();// 断开连接  
  548.               
  549.             return sBuffer.toString();    
  550.         }  
  551.         else {  
  552.               
  553.             return "fail";  
  554.         }  
  555.     }  
  556.   
  557.     /** 
  558.      * md5 加密 
  559.      *  
  560.      * @time 2014年7月10日 下午3:30:01 
  561.      * @param plainText 
  562.      * @return 
  563.      */  
  564.     private String md5Encode(String plainText) {  
  565.         String re_md5 = new String();  
  566.         try {  
  567.             MessageDigest md = MessageDigest.getInstance("MD5");  
  568.             md.update(plainText.getBytes());  
  569.             byte b[] = md.digest();  
  570.             int i;  
  571.             StringBuffer buf = new StringBuffer("");  
  572.             for (int offset = 0; offset < b.length; offset++) {  
  573.                 i = b[offset];  
  574.                 if (i < 0)  
  575.                     i += 256;  
  576.                 if (i < 16)  
  577.                     buf.append("0");  
  578.                 buf.append(Integer.toHexString(i));  
  579.             }  
  580.   
  581.             re_md5 = buf.toString();  
  582.   
  583.         } catch (NoSuchAlgorithmException e) {  
  584.             e.printStackTrace();  
  585.         }  
  586.         return re_md5;  
  587.     }  
  588.   
  589. }  
  590. </span>  

四、前台代码

login.jsp

[html]  view plain  copy
  1. <span style="font-size:18px;"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%  
  3.     String path = request.getContextPath();  
  4.     String basePath = request.getScheme() + "://"  
  5.             + request.getServerName() + ":" + request.getServerPort()  
  6.             + path + "/";  
  7. %>  
  8.   
  9. <!DOCTYPE html>  
  10. <html>  
  11. <head>  
  12.     <meta charset="UTF-8">  
  13.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  14.     <title>gt-node-sdk-demo</title>  
  15.     <style>  
  16.         body {  
  17.             margin: 50px 0;  
  18.             text-align: center;  
  19.             font-family: "PingFangSC-Regular", "Open Sans", Arial, "Hiragino Sans GB", "Microsoft YaHei", "STHeiti", "WenQuanYi Micro Hei", SimSun, sans-serif;  
  20.         }  
  21.         .inp {  
  22.             border: 1px solid #cccccc;  
  23.             border-radius: 2px;  
  24.             padding: 0 10px;  
  25.             width: 278px;  
  26.             height: 40px;  
  27.             font-size: 18px;  
  28.         }  
  29.         .btn {  
  30.             border: 1px solid #cccccc;  
  31.             border-radius: 2px;  
  32.             width: 100px;  
  33.             height: 40px;  
  34.             font-size: 16px;  
  35.             color: #666;  
  36.             cursor: pointer;  
  37.             background: white linear-gradient(180deg, #ffffff 0%, #f3f3f3 100%);  
  38.         }  
  39.         .btn:hover {  
  40.             background: white linear-gradient(0deg, #ffffff 0%, #f3f3f3 100%)  
  41.         }  
  42.         #captcha1,  
  43.         #captcha2 {  
  44.             width: 300px;  
  45.             display: inline-block;  
  46.         }  
  47.         .show {  
  48.             display: block;  
  49.         }  
  50.         .hide {  
  51.             display: none;  
  52.         }  
  53.         #notice1,  
  54.         #notice2 {  
  55.             color: red;  
  56.         }  
  57.         label {  
  58.             vertical-align: top;  
  59.             display: inline-block;  
  60.             width: 80px;  
  61.             text-align: right;  
  62.         }  
  63.         #wait1, #wait2 {  
  64.             text-align: left;  
  65.             color: #666;  
  66.             margin: 0;  
  67.         }  
  68.     </style>  
  69. </head>  
  70. <body>  
  71. <h1>极验验证SDKDemo</h1>  
  72. <hr>  
  73. <form action="gt/ajax-validate1" method="post">  
  74.     <h2>大图点击Demo,使用表单进行二次验证</h2>  
  75.     <br>  
  76.     <div>  
  77.         <label for="username1">用户名:</label>  
  78.         <input class="inp" id="username1" type="text" value="极验验证">  
  79.     </div>  
  80.     <br>  
  81.     <div>  
  82.         <label for="password1">密码:</label>  
  83.         <input class="inp" id="password1" type="password" value="123456">  
  84.     </div>  
  85.     <br>  
  86.     <div>  
  87.         <label>完成验证:</label>  
  88.         <div id="captcha1">  
  89.             <p id="wait1" class="show">正在加载验证码......</p>  
  90.         </div>  
  91.     </div>  
  92.     <br>  
  93.     <p id="notice1" class="hide">请先完成验证</p>  
  94.     <input class="btn" id="submit1" type="submit" value="提交">  
  95. </form>  
  96.   
  97. <!-- 注意,验证码本身是不需要 jquery 库,此处使用 jquery 仅为了在 demo 使用,减少代码量 -->  
  98. <script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.js"></script>  
  99.   
  100. <!-- 引入 gt.js,既可以使用其中提供的 initGeetest 初始化函数 -->  
  101. <script src="<%=request.getContextPath() %>/gt.js"></script>  
  102.   
  103. <script>  
  104.     var handler1 = function (captchaObj) {  
  105.         $("#submit1").click(function (e) {  
  106.             var result = captchaObj.getValidate();  
  107.             if (!result) {  
  108.                 $("#notice1").show();  
  109.                 setTimeout(function () {  
  110.                     $("#notice1").hide();  
  111.                 }, 2000);  
  112.                 e.preventDefault();  
  113.             }  
  114.         });  
  115.         // 将验证码加到id为captcha的元素里,同时会有三个input的值用于表单提交  
  116.         captchaObj.appendTo("#captcha1");  
  117.         captchaObj.onReady(function () {  
  118.             $("#wait1").hide();  
  119.         });  
  120.         // 更多接口参考:http://www.geetest.com/install/sections/idx-client-sdk.html  
  121.     };  
  122.     $.ajax({  
  123.         url: "gt/register1?t=" + (new Date()).getTime(), // 加随机数防止缓存  
  124.         type: "get",  
  125.         dataType: "json",  
  126.         success: function (data) {  
  127.             // 调用 initGeetest 初始化参数  
  128.             // 参数1:配置参数  
  129.             // 参数2:回调,回调的第一个参数验证码对象,之后可以使用它调用相应的接口  
  130.             initGeetest({  
  131.                 gt: data.gt,  
  132.                 challenge: data.challenge,  
  133.                 new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机  
  134.                 offline: !data.success, // 表示用户后台检测极验服务器是否宕机,一般不需要关注  
  135.                 product: "float", // 产品形式,包括:float,popup  
  136.                 width: "100%"  
  137.                 // 更多配置参数请参见:http://www.geetest.com/install/sections/idx-client-sdk.html#config  
  138.             }, handler1);  
  139.         }  
  140.     });  
  141. </script>  
  142. <br><br>  
  143. <hr>  
  144. <form>  
  145.     <h2>滑动demo,使用ajax进行二次验证</h2>  
  146.     <br>  
  147.     <div>  
  148.         <label for="username2">用户名:</label>  
  149.         <input class="inp" id="username2" type="text" value="极验验证">  
  150.     </div>  
  151.     <br>  
  152.     <div>  
  153.         <label for="password2">密码:</label>  
  154.         <input class="inp" id="password2" type="password" value="123456">  
  155.     </div>  
  156.     <br>  
  157.     <div>  
  158.         <label>完成验证:</label>  
  159.         <div id="captcha2">  
  160.             <p id="wait2" class="show">正在加载验证码......</p>  
  161.         </div>  
  162.     </div>  
  163.     <br>  
  164.     <p id="notice2" class="hide">请先完成验证</p>  
  165.     <input class="btn" id="submit2" type="submit" value="提交">  
  166. </form>  
  167. <script>  
  168.     var handler2 = function (captchaObj) {  
  169.         $("#submit2").click(function (e) {  
  170.             var result = captchaObj.getValidate();  
  171.             if (!result) {  
  172.                 $("#notice2").show();  
  173.                 setTimeout(function () {  
  174.                     $("#notice2").hide();  
  175.                 }, 2000);  
  176.             } else {  
  177.                 $.ajax({  
  178.                     url: 'gt/ajax-validate2',  
  179.                     type: 'POST',  
  180.                     dataType: 'json',  
  181.                     data: {  
  182.                         username: $('#username2').val(),  
  183.                         password: $('#password2').val(),  
  184.                         geetest_challenge: result.geetest_challenge,  
  185.                         geetest_validate: result.geetest_validate,  
  186.                         geetest_seccode: result.geetest_seccode  
  187.                     },  
  188.                     success: function (data) {  
  189.                         if (data.status === 'success') {  
  190.                             alert('登录成功');  
  191.                         } else if (data.status === 'fail') {  
  192.                             alert('登录失败');  
  193.                         }  
  194.                     }  
  195.                 })  
  196.             }  
  197.             e.preventDefault();  
  198.         });  
  199.         // 将验证码加到id为captcha的元素里,同时会有三个input的值用于表单提交  
  200.         captchaObj.appendTo("#captcha2");  
  201.         captchaObj.onReady(function () {  
  202.             $("#wait2").hide();  
  203.         });  
  204.         // 更多接口参考:http://www.geetest.com/install/sections/idx-client-sdk.html  
  205.     };  
  206.     $.ajax({  
  207.         url: "gt/register2?t=" + (new Date()).getTime(), // 加随机数防止缓存  
  208.         type: "get",  
  209.         dataType: "json",  
  210.         success: function (data) {  
  211.             // 调用 initGeetest 初始化参数  
  212.             // 参数1:配置参数  
  213.             // 参数2:回调,回调的第一个参数验证码对象,之后可以使用它调用相应的接口  
  214.             initGeetest({  
  215.                 gt: data.gt,  
  216.                 challenge: data.challenge,  
  217.                 new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机  
  218.                 offline: !data.success, // 表示用户后台检测极验服务器是否宕机,一般不需要关注  
  219.                 product: "popup", // 产品形式,包括:float,popup  
  220.                 width: "100%"  
  221.                 // 更多配置参数请参见:http://www.geetest.com/install/sections/idx-client-sdk.html#config  
  222.             }, handler2);  
  223.         }  
  224.     });  
  225. </script>  
  226. </body>  
  227. </html></span>  

需要一个js文件,gt.js

运行结果

转载自:http://blog.csdn.net/junmoxi/article/details/77568122?locationNum=10&fps=1

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值