极限验证vue geetestt 又有新破解版了,有人试过没有,到底是不是真的

第三方接口调用(1)
首先是官方的demo
&%@ page language=&java& import=&java.util.*& pageEncoding=&utf-8&%&
String path = request.getContextPath();
String basePath = request.getScheme() + &://&
+ request.getServerName() + &:& + request.getServerPort()
+ path + &/&;
&!doctype html&
&base href=&&%=basePath%&&&
&title&极意网络&/title&
&meta http-equiv=&pragma& content=&no-cache&&
&meta http-equiv=&cache-control& content=&no-cache&&
&meta http-equiv=&expires& content=&0&&
&meta http-equiv=&keywords& content=&keyword1,keyword2,keyword3&&
&meta http-equiv=&description& content=&This is my page&&
&link rel=&stylesheet& type=&text/css& href=&styles.css&&
background-color: #FEFEFE;
width: 960
margin: 100
font-size: 125%;
margin: 30px 0;
&script src=&/jquery/1.9.0/jquery.js&&&/script&
&div class=&wrap&&
&h1&JavaEE站点安装Demo页面&/h1&
&form method=&post& action=&VerifyLoginServlet&&
&div class=&row&&
&label for=&name&&邮箱&/label& &input type=&text& id=&email&
name=&email& value=&& /&
&div class=&row&&
&label for=&passwd&&密码&/label& &input type=&password& id=&passwd&
name=&passwd& value=&gggggggg& /&
&div class=&row&&
&div id=&div_geetest_lib&&&/div&
&div id=&div_id_embed&&&/div&
&div class=&row&&
&input type=&submit& value=&登录& id=&submit-button& /&
&script type=&text/javascript&&
function geetest_ajax_results() {
//TODO, not necessory a geetest ajax demo,
url : &/todo/VerifyLoginServlet&,//todo:set the servelet of your own
type : &post&,
data : gt_captcha_obj.getValidate(),
success : function(sdk_result) {
console.log(sdk_result)
var gtFailbackFrontInitial = function(result) {
var s = document.createElement('script');
s.id = 'gt_lib';
s.src = '/static/js/geetest.0.0.0.js';
s.charset = 'UTF-8';
s.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(s);
s.onload = s.onreadystatechange = function() {
if (!loaded
&& (!this.readyState
|| this.readyState === 'loaded' || this.readyState === 'complete')) {
loadGeetest(result);
geetest server status, use the failback solution
var loadGeetest = function(config) {
//1. use geetest captcha
window.gt_captcha_obj = new window.Geetest({
gt : config.gt,
challenge : config.challenge,
product : 'embed',
offline : !config.success
gt_captcha_obj.appendTo(&#div_id_embed&);
//Ajax request demo,if you use submit form ,then ignore it
gt_captcha_obj.onSuccess(function() {
geetest_ajax_results()
s = document.createElement('script');
s.src = '/get.php?callback=gtcallback';
$(&#div_geetest_lib&).append(s);
var gtcallback =( function() {
var status = 0, result, apiF
return function(r) {
status += 1;
setTimeout(function() {
if (!window.Geetest) {
gtFailbackFrontInitial(result)
else if(apiFail) {
if (status == 2) {
loadGeetest(result);
url : &StartCaptchaServlet&,
type : &get&,
dataType : 'JSON',
success : function(result) {
gtcallback(result)
package com.geetest.sdk.
import java.io.BufferedR
import java.io.BufferedW
import java.io.IOE
import java.io.InputS
import java.io.InputStreamR
import java.io.OutputStreamW
import java.net.HttpURLC
import java.net.InetA
import java.net.S
import java.net.URL;
import java.security.MessageD
import java.security.NoSuchAlgorithmE
import java.text.SimpleDateF
import java.util.ArrayL
import java.util.HashM
import javax.servlet.http.HttpServletR
* Java SDK
* @author Zheng
* @time 日 下午3:29:09
public class GeetestLib {
* SDK版本编号
// private final int verCode = 8;
* SDK版本名称
protected final String verName = &2.15.10.9.1&;
protected final String sdkLang = &java&;// SD的语言类型
protected final static String gt_session_key = &geetest&;// geetest对象存储的session的key值(单实例)
protected final static String gt_server_status_session_key = &gt_server_status&;// 极验服务器状态key值(单实例)
protected final String baseUrl = &&;
protected final String api_url = &http://& + baseU
protected final String https_api_url = &https://& + baseU// 一些页面是https
protected final int com_port = 80;// 通讯端口号
protected final int defaultIsMobile = 0;
// private final int defaultMobileWidth = 260;// the default width of the
// mobile id
// 一些常量
public static final String success_res = &success&;
public static final String fail_res = &fail&;
public static final String forbidden_res = &forbidden&;
// 前端验证的表单值--属于接口,不允许修改
protected final String fn_geetest_challenge = &geetest_challenge&;
protected final String fn_geetest_validate = &geetest_validate&;
protected final String fn_geetest_seccode = &geetest_seccode&;
protected Boolean debugCode =// 调试开关,是否输出调试日志
protected String validateLogPath = &&;// 服务器端保存日志的目录//var/log/,请确保有可读写权限
private String captchaId = &&;
private String privateKey = &&;
* the challenge
private String challengeId = &&;
* set the own private pictures,default is &&
private String picId = &&;
* he captcha product type,default is 'embed'
private String productType = &embed&;
* is secure
private Boolean isHttps =
public Boolean getIsHttps() {
return isH
public void setIsHttps(Boolean isHttps) {
this.isHttps = isH
* when the productType is popup,it needs to set the submitbutton
private String submitBtnId = &submit-button&;
public String getSubmitBtnId() {
return submitBtnId;
public void setSubmitBtnId(String submitBtnId) {
this.submitBtnId = submitBtnId;
* 是否是移动端的
private int isMobile = defaultIsM// 1--true,0-false
public String getChallengeId() {
return challengeId;
public void setChallengeId(String challengeId) {
this.challengeId = challengeId;
public final Boolean getDebugCode() {
return debugC
public final void setDebugCode(Boolean debugCode) {
this.debugCode = debugC
* 获取版本编号
* @author Zheng
* @time 日 上午11:07:11
public String getVersionInfo() {
return verN
public String getValidateLogPath() {
return validateLogP
public void setValidateLogPath(String validateLogPath) {
this.validateLogPath = validateLogP
// public void setCaptcha_id(String captcha_id) {
// this.captcha_id = captcha_
* 一个无参构造函数
public GeetestLib() {
// public static GeetestLib createGtInstance() {
// GeetestLib geetestSdk = new GeetestLib();
// geetestSdk.setCaptchaId(GeetestConfig.getCaptcha_id());
// geetestSdk.setPrivateKey(GeetestConfig.getPrivate_key());
// return geetestS
* 将当前实例设置到session中
* @param request
public void setGtSession(HttpServletRequest request) {
request.getSession().setAttribute(gt_session_key, this);// set session
this.gtlog(&set session succeed&);
* 同一会话多实例时,设置session
* @param request
* @param gt_instance_session_key
不同验证实例设置的key
public void setGtSession(HttpServletRequest request,
String gt_instance_session_key) {
request.getSession().setAttribute(gt_instance_session_key, this);// set
// session
this.gtlog(&set session succeed&);
* 极验服务器的gt-server状态值
* @param request
public void setGtServerStatusSession(HttpServletRequest request,
int statusCode) {
request.getSession().setAttribute(gt_server_status_session_key,
statusCode);// set session
* 极验服务器的gt-server状态值(多实例)
* @param request
* @param statusCode
* @param gt_instance_server_status_session_key
public void setGtServerStatusSession(HttpServletRequest request,
int statusCode, String gt_instance_server_status_session_key) {
request.getSession().setAttribute(
gt_instance_server_status_session_key, statusCode);// set
// session
* 获取session
* @param request
public static GeetestLib getGtSession(HttpServletRequest request) {
return (GeetestLib) request.getSession().getAttribute(gt_session_key);
* 获取session(用于同一会话多实例模式下,做的区分)
* @param request
* @param gt_instance_session_key
public static GeetestLib getGtSession(HttpServletRequest request,
String gt_instance_session_key) {
return (GeetestLib) request.getSession().getAttribute(
gt_instance_session_key);
* 0表示不正常,1表示正常
* @param request
public static int getGtServerStatusSession(HttpServletRequest request) {
return (Integer) request.getSession().getAttribute(
gt_server_status_session_key);
* 获取session(用于同一会话多实例模式下,做的区分)
* @param request
* @param gt_instance_server_status_session_key
public static int getGtServerStatusSession(HttpServletRequest request,
String gt_instance_server_status_session_key) {
return (Integer) request.getSession().getAttribute(
gt_instance_server_status_session_key);
* 预处理失败后的返回格式串
public String getFailPreProcessRes() {
// return String.format(&{\&success\&:%s}&, 0);
Long rnd1 = Math.round(Math.random() * 100);
Long rnd2 = Math.round(Math.random() * 100);
String md5Str1 = md5Encode(rnd1 + &&);
String md5Str2 = md5Encode(rnd2 + &&);
String challenge = md5Str1 + md5Str2.substring(0, 2);
this.setChallengeId(challenge);
return String.format(
&{\&success\&:%s,\&gt\&:\&%s\&,\&challenge\&:\&%s\&}&, 0,
this.getCaptchaId(), this.getChallengeId());
* 预处理成功后的标准串
public String getSuccessPreProcessRes() {
return String.format(
&{\&success\&:%s,\&gt\&:\&%s\&,\&challenge\&:\&%s\&}&, 1,
this.getCaptchaId(), this.getChallengeId());
* 保存验证的日志,方便后续和极验做一些联调工作,用于可能有前端验证通过,但是后面验证失败的情况
* @param challenge
* @param validate
* @param seccode
* @param gtUser
用户页面的cookie标识
* @param sdkResult
public void saveValidateLog(String challenge, String validate,
String seccode, String sdkResult) {
SimpleDateFormat sDateFormat = new SimpleDateFormat(
&yyyy-MM-dd
hh:mm:ss&);
String date = sDateFormat.format(new java.util.Date());
String logFormat = String.format(
&date:%s,challenge:%s,validate:%s,seccode:%s,sdkResult:%s&,
date, challenge, validate, seccode, sdkResult);
gtlog(logFormat);
public String getPicId() {
return picId;
public void setPicId(String picId) {
this.picId = picId;
public String getProductType() {
return productT
public void setProductType(String productType) {
this.productType = productT
public int getIsMobile() {
return isM
public void setIsMobile(int isMobile) {
this.isMobile = isM
public String getPrivateKey() {
return privateK
public void setPrivateKey(String privateKey) {
this.privateKey = privateK
public GeetestLib(String privateKey) {
this.privateKey = privateK
// public GeetestLib(String privateKey, String captcha_id) {
// this.privateKey = privateK
// this.captcha_id = captcha_
// public int getVerCode() {
// return verC
public String getVerName() {
return verN
public String getCaptchaId() {
return captchaId;
public void setCaptchaId(String captchaId) {
this.captchaId = captchaId;
* processing before the captcha display on the web front
public int preProcess() {
// first check the server status , to handle failback
// if (getGtServerStatus() != 1) {
// return 0;
// just check the server side register
if (registerChallenge() != 1) {
* generate the dynamic front source
* @param different
product display mode :float,embed,popup
public String getGtFrontSource() {
String base_path = &&;
if (this.isHttps) {
base_path = this.https_api_
base_path = this.api_
String frontSource = String.format(
&&script type=\&text/javascript\& src=\&%s/get.php?&
+ &gt=%s&challenge=%s&, base_path, this.captchaId,
this.challengeId);
if (this.productType.equals(&popup&)) {
frontSource += String.format(&&product=%s&popupbtnid=%s&,
this.productType, this.submitBtnId);
frontSource += String.format(&&product=%s&, this.productType);
frontSource += &\&&&/script&&;
return frontS
* 获取极验的服务器状态
* @author Zheng
* @time 日 下午7:12:38
public int getGtServerStatus() {
final String GET_URL = api_url + &/check_status.php&;
if (readContentFromGet(GET_URL).equals(&ok&)) {
System.out.println(&gServer is Down&);
} catch (Exception e) {
e.printStackTrace();
* generate a random num
public int getRandomNum() {
int rand_num = (int) (Math.random() * 100);
// System.out.print(rand_num);
return rand_
* Register the challenge
public int registerChallenge() {
String GET_URL = api_url + &/register.php?gt=& + this.captchaId;
// if (this.productType.equals(&popup&)) {
// GET_URL += String.format(&&product=%s&popupbtnid=%s&,
// this.productType, this.submitBtnId);
// } else {
// GET_URL += String.format(&&product=%s&, this.productType);
// System.out.print(GET_URL);
String result_str = readContentFromGet(GET_URL);
// System.out.println(result_str);
if (32 == result_str.length()) {
this.challengeId = result_
System.out.println(&gServer register challenge failed&);
} catch (Exception e) {
gtlog(&exception:register api:&);
// e.printStackTrace();
* 读取服务器
* @author Zheng
* @time 日 下午7:11:11
* @param getURL
* @throws IOException
private String readContentFromGet(String getURL) throws IOException {
URL getUrl = new URL(getURL);
HttpURLConnection connection = (HttpURLConnection) getUrl
.openConnection();
connection.setConnectTimeout(2000);// 设置连接主机超时(单位:毫秒)
connection.setReadTimeout(2000);// 设置从主机读取数据超时(单位:毫秒)
// 建立与服务器的连接,并未发送数据
connection.connect();
// 发送数据到服务器并使用Reader读取返回的数据
StringBuffer sBuffer = new StringBuffer();
InputStream inStream =
byte[] buf = new byte[1024];
inStream = connection.getInputStream();
for ( (n = inStream.read(buf)) != -1;) {
sBuffer.append(new String(buf, 0, n, &UTF-8&));
inStream.close();
connection.disconnect();// 断开连接
return sBuffer.toString();
* 判断一个表单对象值是否为空
* @time 日 下午5:54:25
* @param gtObj
protected boolean objIsEmpty(Object gtObj) {
if (gtObj == null) {
if (gtObj.toString().trim().length() == 0) {
// && gtObj.toString().trim().length() & 0
* 检查客户端的请求是否为空--三个只要有一个为空,则判断不合法
* @time 日 下午5:46:34
* @param request
public boolean resquestIsLegal(HttpServletRequest request) {
if (objIsEmpty(request.getParameter(this.fn_geetest_challenge))) {
if (objIsEmpty(request.getParameter(this.fn_geetest_validate))) {
if (objIsEmpty(request.getParameter(this.fn_geetest_seccode))) {
* 检验验证请求 传入的参数为request--vCode 8之后不再更新,不推荐使用
* @time 日 下午6:34:55
* @param request
public boolean validateRequest(HttpServletRequest request) {
boolean gtResult = this.validate(
request.getParameter(this.fn_geetest_challenge),
request.getParameter(this.fn_geetest_validate),
request.getParameter(this.fn_geetest_seccode));
return gtR
* failback使用的验证方式
* @param request
public String failbackValidateRequest(HttpServletRequest request) {
gtlog(&in failback validate&);
if (!resquestIsLegal(request)) {
return GeetestLib.fail_
String challenge = request.getParameter(this.fn_geetest_challenge);
String validate = request.getParameter(this.fn_geetest_validate);
// String seccode = request.getParameter(this.fn_geetest_seccode);
if (!challenge.equals(this.getChallengeId())) {
return GeetestLib.fail_
String[] validateStr = validate.split(&_&);
String encodeAns = validateStr[0];
String encodeFullBgImgIndex = validateStr[1];
String encodeImgGrpIndex = validateStr[2];
gtlog(String.format(
&encode----challenge:%s--ans:%s,bg_idx:%s,grp_idx:%s&,
challenge, encodeAns, encodeFullBgImgIndex, encodeImgGrpIndex));
int decodeAns = decodeResponse(this.getChallengeId(), encodeAns);
int decodeFullBgImgIndex = decodeResponse(this.getChallengeId(),
encodeFullBgImgIndex);
int decodeImgGrpIndex = decodeResponse(this.getChallengeId(),
encodeImgGrpIndex);
gtlog(String.format(&decode----ans:%s,bg_idx:%s,grp_idx:%s&, decodeAns,
decodeFullBgImgIndex, decodeImgGrpIndex));
String validateResult = validateFailImage(decodeAns,
decodeFullBgImgIndex, decodeImgGrpIndex);
if (!validateResult.equals(GeetestLib.fail_res)) {
// 使用一随机标识来丢弃掉此次验证,防止重放
Long rnd1 = Math.round(Math.random() * 100);
String md5Str1 = md5Encode(rnd1 + &&);
this.setChallengeId(md5Str1);
return validateR
* @param ans
* @param full_bg_index
* @param img_grp_index
private String validateFailImage(int ans, int full_bg_index,
int img_grp_index) {
final int thread = 3;// 容差值
String full_bg_name = md5Encode(full_bg_index + &&).substring(0, 9);
String bg_name = md5Encode(img_grp_index + &&).substring(10, 19);
String answer_decode = &&;
// 通过两个字符串奇数和偶数位拼接产生答案位
for (int i = 0; i & 9; i++) {
if (i % 2 == 0) {
answer_decode += full_bg_name.charAt(i);
} else if (i % 2 == 1) {
answer_decode += bg_name.charAt(i);
gtlog(&exception&);
String x_decode = answer_decode.substring(4, answer_decode.length());
int x_int = Integer.valueOf(x_decode, 16);// 16 to 10
int result = x_int % 200;
if (result & 40) {
result = 40;
if (Math.abs(ans - result) &= thread) {
return GeetestLib.success_
return GeetestLib.fail_
* 输入的两位的随机数字,解码出偏移量
* @param randStr
public int decodeRandBase(String challenge) {
String base = challenge.substring(32, 34);
ArrayList&Integer& tempArray = new ArrayList&Integer&();
for (int i = 0; i & base.length(); i++) {
char tempChar = base.charAt(i);
Integer tempAscii = (int) (tempChar);
Integer result = (tempAscii & 57) ? (tempAscii - 87)
: (tempAscii - 48);
tempArray.add(result);
int decodeRes = tempArray.get(0) * 36 + tempArray.get(1);
return decodeR
* 解码随机参数
* @param encodeStr
* @param challenge
public int decodeResponse(String challenge, String string) {
if (string.length() & 100) {
int[] shuzi = new int[] { 1, 2, 5, 10, 50 };
String chongfu = &&;
HashMap&String, Integer& key = new HashMap&String, Integer&();
int count = 0;
for (int i = 0; i & challenge.length(); i++) {
String item = challenge.charAt(i) + &&;
if (chongfu.contains(item) == true) {
int value = shuzi[count % 5];
chongfu +=
key.put(item, value);
int res = 0;
for (int j = 0; j & string.length(); j++) {
res += key.get(string.charAt(j) + &&);
res = res - decodeRandBase(challenge);
* 增强版的验证信息,提供了更多的验证返回结果信息,以让客户服务器端有不同的数据处理。
* @param challenge
* @param validate
* @param seccode
public String enhencedValidateRequest(HttpServletRequest request) {
if (!resquestIsLegal(request)) {
return GeetestLib.fail_
String challenge = request.getParameter(this.fn_geetest_challenge);
String validate = request.getParameter(this.fn_geetest_validate);
String seccode = request.getParameter(this.fn_geetest_seccode);
// String gtuser = &&;
// Cookie[] cookies = request.getCookies();
// if (cookies != null) {
// for (int i = 0; i & cookies. i++) {
// Cookie cookie = cookies[i];
// if (&GeeTestUser&.equals(cookie.getName())) {
// gtuser = cookie.getValue();
// gtlog(String.format(&GeeTestUser:%s&, gtuser));
String host = baseU
String path = &/validate.php&;
int port = 80;
// String query = &seccode=& + seccode + &&sdk=& + this.sdkLang + &_&
// + this.verN
String query = String.format(&seccode=%s&sdk=%s&, seccode,
(this.sdkLang + &_& + this.verName));
String response = &&;
gtlog(query);
if (validate.length() &= 0) {
return GeetestLib.fail_
if (!checkResultByPrivate(challenge, validate)) {
return GeetestLib.fail_
response = postValidate(host, path, query, port);
gtlog(&response: & + response);
} catch (Exception e) {
e.printStackTrace();
gtlog(&md5: & + md5Encode(seccode));
if (response.equals(md5Encode(seccode))) {
return GeetestLib.success_
* the old api use before version code 8(not include)
* @param challenge
* @param validate
* @param seccode
* @time 529 by zheng
private boolean validate(String challenge, String validate, String seccode) {
String host = baseU
String path = &/validate.php&;
int port = 80;
if (validate.length() & 0 && checkResultByPrivate(challenge, validate)) {
String query = &seccode=& +
String response = &&;
response = postValidate(host, path, query, port);
gtlog(response);
} catch (Exception e) {
e.printStackTrace();
gtlog(&md5: & + md5Encode(seccode));
if (response.equals(md5Encode(seccode))) {
* Print out log message Use to Debug
* @time 829 by zheng
* @param message
public void gtlog(String message) {
if (debugCode) {
System.out.println(&gtlog: & + message);
protected boolean checkResultByPrivate(String challenge, String validate) {
String encodeStr = md5Encode(privateKey + &geetest& + challenge);
return validate.equals(encodeStr);
* fuck,貌似不是Post方式,后面重构时修改名字
* @param host
* @param path
* @param data
* @param port
* @throws Exception
protected String postValidate(String host, String path, String data,
int port) throws Exception {
String response = &error&;
// data=fixEncoding(data);
InetAddress addr = InetAddress.getByName(host);
Socket socket = new Socket(addr, port);
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream(), &UTF8&));
wr.write(&POST & + path + & HTTP/1.0\r\n&);
wr.write(&Host: & + host + &\r\n&);
wr.write(&Content-Type: application/x-www-form-urlencoded\r\n&);
wr.write(&Content-Length: & + data.length() + &\r\n&);
wr.write(&\r\n&); // 以空行作为分割
// 发送数据
wr.write(data);
wr.flush();
// 读取返回信息
BufferedReader rd = new BufferedReader(new InputStreamReader(
socket.getInputStream(), &UTF-8&));
while ((line = rd.readLine()) != null) {
System.out.println(line);
response =
wr.close();
rd.close();
socket.close();
// * 转为UTF8编码
// * @time 日 下午3:29:45
// * @param str
// * @return
// * @throws UnsupportedEncodingException
// private String fixEncoding(String str) throws
// UnsupportedEncodingException {
// String tempStr = new String(str.getBytes(&UTF-8&));
// return URLEncoder.encode(tempStr, &UTF-8&);
* md5 加密
* @time 日 下午3:30:01
* @param plainText
public String md5Encode(String plainText) {
String re_md5 = new String();
MessageDigest md = MessageDigest.getInstance(&MD5&);
md.update(plainText.getBytes());
byte b[] = md.digest();
StringBuffer buf = new StringBuffer(&&);
for (int offset = 0; offset & b. offset++) {
i = b[offset];
if (i & 0)
if (i & 16)
buf.append(&0&);
buf.append(Integer.toHexString(i));
re_md5 = buf.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return re_md5;
package com.geetest.sdk.java.web.
import java.io.IOE
import java.io.PrintW
import javax.servlet.ServletE
import javax.servlet.http.HttpS
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
import com.geetest.sdk.java.GeetestL
public class VerifyLoginServlet extends HttpServlet {
private static final long serialVersionUID = 893949L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// get session to share the object
GeetestLib geetest = GeetestLib.getGtSession(request);
int gt_server_status_code = GeetestLib
.getGtServerStatusSession(request);
String gtResult = &fail&;
if (gt_server_status_code == 1) {
gtResult = geetest.enhencedValidateRequest(request);
System.out.println(gtResult);
// TODO use you own system when geetest-server is down:failback
System.out.println(&failback:use your own server captcha validate&);
gtResult = &fail&;
gtResult=geetest.failbackValidateRequest(request);
if (gtResult.equals(GeetestLib.success_res)) {
// TODO handle the Success result
PrintWriter out = response.getWriter();
out.println(GeetestLib.success_res + &:& + geetest.getVersionInfo());
} else if (gtResult.equals(GeetestLib.forbidden_res)) {
// TODO handle the Forbidden result
PrintWriter out = response.getWriter();
out.println(GeetestLib.forbidden_res + &:&
+ geetest.getVersionInfo());
// TODO handle the Fail result
PrintWriter out = response.getWriter();
out.println(GeetestLib.fail_res + &:& + geetest.getVersionInfo());
package com.geetest.sdk.java.web.
import java.io.IOE
import java.io.PrintW
import javax.servlet.ServletE
import javax.servlet.http.HttpS
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
import com.geetest.sdk.java.GeetestL
public class VerifyLoginServlet extends HttpServlet {
private static final long serialVersionUID = 893949L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// get session to share the object
GeetestLib geetest = GeetestLib.getGtSession(request);
int gt_server_status_code = GeetestLib
.getGtServerStatusSession(request);
String gtResult = &fail&;
if (gt_server_status_code == 1) {
gtResult = geetest.enhencedValidateRequest(request);
System.out.println(gtResult);
// TODO use you own system when geetest-server is down:failback
System.out.println(&failback:use your own server captcha validate&);
gtResult = &fail&;
gtResult=geetest.failbackValidateRequest(request);
if (gtResult.equals(GeetestLib.success_res)) {
// TODO handle the Success result
PrintWriter out = response.getWriter();
out.println(GeetestLib.success_res + &:& + geetest.getVersionInfo());
} else if (gtResult.equals(GeetestLib.forbidden_res)) {
// TODO handle the Forbidden result
PrintWriter out = response.getWriter();
out.println(GeetestLib.forbidden_res + &:&
+ geetest.getVersionInfo());
// TODO handle the Fail result
PrintWriter out = response.getWriter();
out.println(GeetestLib.fail_res + &:& + geetest.getVersionInfo());
改造的spring版本
@RequestMapping(value = &/loginVerifyPrepare&, method = RequestMethod.GET)
@ResponseBody
public Object loginVerifyPrepare(HttpServletRequest request) {
GeetestLib gtSdk = new GeetestLib();
gtSdk.setCaptchaId(GeetestConfig.getCaptcha_id());
gtSdk.setPrivateKey(GeetestConfig.getPrivate_key());
gtSdk.setGtSession(request);
String resStr = &{}&;
if (gtSdk.preProcess() == 1) {
// gt server is in use
resStr = gtSdk.getSuccessPreProcessRes();
gtSdk.setGtServerStatusSession(request, 1);
// gt server is down
resStr = gtSdk.getFailPreProcessRes();
gtSdk.setGtServerStatusSession(request, 0);
return resS
@RequestMapping(value = &/loginVerifyResult&, method = RequestMethod.POST)
@ResponseBody
public Object loginVerifyResult(HttpServletRequest request) {
// get session to share the object
GeetestLib geetest = GeetestLib.getGtSession(request);
int gt_server_status_code = GeetestLib.getGtServerStatusSession(request);
String gtResult = &fail&;
if (gt_server_status_code == 1) {
gtResult = geetest.enhencedValidateRequest(request);
(&gtResult : & + gtResult);
// use you own system when geetest-server is down:failback
(&failback:use your own server captcha validate&);
gtResult = &fail&;
if (gtResult.equals(GeetestLib.success_res)) {
// handle the Success result
return GeetestLib.success_res + &:& + geetest.getVersionInfo();
} else if (gtResult.equals(GeetestLib.forbidden_res)) {
// handle the Forbidden result
return GeetestLib.forbidden_res + &:& + geetest.getVersionInfo();
// handle the Fail result
return GeetestLib.fail_res + &:& + geetest.getVersionInfo();
&!DOCTYPE html&
&html xmlns=&http://www.w3.org/1999/xhtml&&
#include(&/resources/common/header.html&)
&link href=&/resources/css/login.css& rel=&stylesheet& /&
&script src=&/resources/plugin/jquery/js/jquery.cookie.js&&&/script&
&script src=&/resources/plugin/notify/js/notify.min.js&&&/script&
&script src=&/get.php&&&/script&
&form id=&loginForm& method=&post&&
&div class=&login-container animated fadeInDown&&
&div class=&loginbox bg-white&&
&div class=&loginbox-title&&
&strong&旭航商店运营平台&/strong&
&div class=&loginbox-textbox&&
&i class=&loginbox-icon glyphicon glyphicon-user&&&/i&&input type=&text& id=&loginname& name=&loginname& class=&form-control& placeholder=&用户名& /&
&div class=&loginbox-textbox&&
&i class=&loginbox-icon glyphicon glyphicon-lock&&&/i&&input type=&password& id=&password& name=&password& class=&form-control& placeholder=&密码& /&
&div id=&div_verify& class=&verifybox&&&/div&
&div id=&div_captcha& class=&loginbox-textbox&&
&input type=&text& id=&captchaInput& class=&form-control captchaInput& maxlength=&4& /&&img id=&captchaImage& class=&captchaImage& title=&等待刷新& /&
&div class=&loginbox-textbox&&
&div class=&checkbox&&
&label&&input id=&checkRemember& type=&checkbox&&记住密码&/label&
&label class=&label-right&&&input id=&checkPasswordVisible& type=&checkbox&&显示密码&/label&
&div class=&loginbox-submit&&
&input type=&button& id=&btnLogin& class=&btn btn-primary btn-block& disabled=&disabled& value=&登
&p class=&copyright&&Copyright(C)2014 Hangzhou XuHang Technology Co. Ltd. All Rights Reserved.&/p&
&script type=&text/javascript&&
var verifyResult =
var verifyDefault =
var tagKeepRemember = &keepRemember&;
var tagLoginname = &loginname&;
var tagPassword = &password&;
var loginnameCookie, passwordC
var notifyOptions4Show = {
autoHide : false,
position : &right&,
className : &error&,
style : &bootstrap&,
showDuration : 400,
hideDuration : 200,
var notifyOptions4Hide = {
autoHide : true,
showDuration : 0,
hideDuration : 0,
$(function() {
// 重新跳转登录
// if (top.window.location.href != window.location.href) {
if (window != top) {
top.window.location.href = window.location.
var inited = initCookie();
var loginnameRedirect = &${loginnameRedirect}&;
if (loginnameRedirect) {
$(&#loginname&).val(loginnameRedirect);
$(&#password&).val(&&);
$(&#password&).focus();
if (!inited) {
if ($(&#loginname&).val()) {
$(&#password&).focus();
$(&#loginname&).focus();
// get geetest server status, use the failback solution
url : &${urlLoginVerifyPrepare}&,
type : &get&,
dataType : 'JSON',
success : function(result) {
$(&#btnLogin&).removeAttr(&disabled&);
if (result.success) {
verifyDefault =
$(&#div_captcha&).hide();
//1. use geetest capthca
window.gt_captcha_obj = new window.Geetest({
gt : result.gt,
challenge : result.challenge,
product : 'float'
gt_captcha_obj.appendTo(&#div_verify&);
//Ajax request demo,if you use submit form ,then ignore it
gt_captcha_obj.onSuccess(function() {
geetest_ajax_results()
gt_captcha_obj.onStatusChange(function() {
$(&#div_verify&).notify(&&, notifyOptions4Hide);
//failback :use your own captcha template
//Geetest Server is down,Please use your own captcha system in your web page
//or use the simple geetest failback solution
verifyDefault =
refreshCaptchaImage();
$(&#checkPasswordVisible&).change(function() {
if (this.checked) {
$(&#password&).attr(&type&, &text&);
$(&#password&).attr(&type&, &password&);
$(&#loginname&).off(&input propertychange&).on(&input propertychange&, function() {
$(&#password&).val(&&);
checkItemTrigger(&checkRemember&, false);
if ($(this).val() == loginnameCookie && passwordCookie) {
$(&#password&).val(passwordCookie);
checkItemTrigger(&checkRemember&, true);
/*$(document).keyup(function(e) {
var event = e || window.
var code = event.keyCode || event.which || event.charC
if (code == 13) {
$(document).keydown(function(e) {
var event = e || window.
var code = event.keyCode || event.which || event.charC
if (code == 13) {
if ($(&#loginname&).is(&:focus&)) {
$(&#loginname&).notify(&&, notifyOptions4Hide);
} else if ($(&#password&).is(&:focus&)) {
$(&#password&).notify(&&, notifyOptions4Hide);
if (!verifyDefault) {
if ($(&#captchaInput&).is(&:focus&)) {
$(&#captchaImage&).notify(&&, notifyOptions4Hide);
$(&#btnLogin&).click(function() {
$(&#captchaImage&).click(function() {
refreshCaptchaImage();
function initCookie() {
var keepRemember = $.cookie(tagKeepRemember);
var loginname = loginnameCookie = $.cookie(tagLoginname);
var password = passwordCookie = $.cookie(tagPassword);
if (keepRemember == &true&) {
// $(&#checkRemember&).attr(&checked&, true);
checkItemTrigger(&checkRemember&, true);
if (loginname) {
$(&#loginname&).val(loginname);
$(&#password&).val(password);
// $(&#checkRemember&).attr(&checked&, false);
checkItemTrigger(&checkRemember&, false);
if (loginname) {
$(&#loginname&).val(loginname);
function geetest_ajax_results() {
url : &${urlLoginVerifyResult}&,
type : &post&,
data : gt_captcha_obj.getValidate(),
success : function(sdk_result) {
if (sdk_result.indexOf(&success&) &= 0) {
verifyResult =
function login() {
var loginname = $(&#loginname&).val();
if (!loginname) {
$(&#loginname&).notify(&要填写用户名哟&, notifyOptions4Show);
$(&#loginname&).focus();
var password = $(&#password&).val();
if (!password) {
$(&#password&).notify(&密码未填写&, notifyOptions4Show);
$(&#password&).focus();
if (verifyDefault) {
if (!verifyResult) {
gt_captcha_obj.refresh();
$(&#div_verify&).notify(&请先通过验证&, notifyOptions4Show);
var captchaVal = $(&#captchaInput&).val();
if (!captchaVal) {
$(&#captchaImage&).notify(&请输入验证码&, notifyOptions4Show);
$(&#captchaInput&).focus();
var dataSend = {};
dataSend[&loginname&] =
dataSend[&password&] =
dataSend[&verifyDefault&] = verifyD
dataSend[&captchaVal&] = captchaV
type : &POST&,
url : &${urlLoginCheck}&,
// data : $(&#loginForm&).serialize(), // 序列化
data : dataSend, // { 'loginname':'wander', 'password':'9; },
success : function(data) {
var result = data.
var msg = data.
var idSel = &#& + data.
if (result) {
var keepRemember = $(&#checkRemember&).is(&:checked&);
if (keepRemember) {
$.cookie(tagKeepRemember, &true&);
$.cookie(tagLoginname, loginname);
$.cookie(tagPassword, password);
$.cookie(tagKeepRemember, &false&);
$.cookie(tagLoginname, loginname);
checkLoginConflict(loginname);
$(idSel).notify(msg, notifyOptions4Show);
if (data.obj == &captchaImage&) {
$(&#captchaInput&).focus();
$(idSel).focus();
function refreshCaptchaImage() {
$(&#captchaImage&).hide().attr(&src&, &${urlLoginCaptchaImage}&).fadeIn();
function checkLoginConflict(loginname) {
var websocket = initWebsocket(
// &ws://${macroGet('m_serverName')}:${macroGet('m_onlineUserManagerServerPort')}/&,
&${urlWebsocket}&,
function() {
websocket.send(ONLINE_USER_MANAGER_PRE_ONLINE + ONLINE_USER_MANAGER_SEPARATOR + loginname);
}, function(type, msg) {
if (type == ONLINE_USER_MANAGER_TYPE_ONLINE) {
$(&#btnLogin&).attr(&disabled&, true);
window.location.href = &${urlMain}&;
$(&#loginname&).notify(&此账号已经登录,您暂时无法登录&, notifyOptions4Show);
$(&#loginname&).focus();
}, null, null);
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:652105次
积分:14389
积分:14389
排名:第865名
原创:763篇
转载:192篇
评论:58条
(4)(13)(5)(2)(4)(15)(17)(13)(17)(34)(27)(22)(17)(34)(229)(22)(23)(6)(20)(21)(6)(3)(15)(27)(18)(23)(25)(30)(40)(43)(32)(19)(26)(27)(27)(24)(23)
(window.slotbydup = window.slotbydup || []).push({
id: '4740881',
container: s,
size: '200,200',
display: 'inlay-fix'}

我要回帖

更多关于 geetest 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信