验证码通常是为了区分用户是人还是计算机,也可以防止破解密码、刷票等恶意行为,而客户端上多数会用在关键操作上,比如购买、登录、注册等场景。现在验证码的种类样式也特别多,今天教大家如何用Java做出滑动拼图验证码吧~
接入KgCaptcha
访问凯格行为验证码官网,注册账号后登录控制台,申请开通后系统会分配一个唯一的AppId、AppSecret。
![](https://img-blog.csdnimg.cn/img_convert/c9718fee4a2cadec8036abb87602e2bd.png)
Java代码
package com.kyger;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
publicclassdemoextendsHttpServlet{
privatestaticfinallong serialVersionUID = 1L;
publicdemo(){
super();
}
protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
// 编码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");;
response.setContentType("text/html; charset=utf-8");
// 后台处理if (request.getMethod().equals("POST")){
String html, appId, appSecret;
// 设置 AppId 及 AppSecret,在应用管理中获取
appId = "94dATYQa";
appSecret = "6u2BhEgORjQPkO1c69mpg2z5lLTLHf6a";
KgCaptchaSDK KgRequest = new KgCaptchaSDK(appId, appSecret);
// 前端验证成功后颁发的 token,有效期为两分钟
KgRequest.token = request.getParameter("kgCaptchaToken");
// 填写应用服务域名,在应用管理中获取
KgRequest.appCdn = "https://cdn.kgcaptcha.com";
// 请求超时时间,秒
KgRequest.connectTimeout = 5;
// 用户登录或尝试帐号,当安全策略中的防控等级为3时必须填写,一般情况下可以忽略// 可以填写用户输入的登录帐号(如:request.getParameter("username"),可拦截同一帐号多次尝试等行为
KgRequest.userId = "kgCaptchaDemo";
// request 对象,当安全策略中的防控等级为3时必须填写,一般情况下可以忽略
KgRequest.request = request;
// java 环境中无法提供 request 对象,请分别定义:clientIp|clientBrowser|domain 参数,即:// KgRequest.clientIp = "127.0.0.1"; // 填写客户端IP// KgRequest.clientBrowser = ""; // 客户端浏览器信息// KgRequest.domain = "http://localhost"; // 你的授权域名或服务IP// 发送验证请求
Map<String, String> requestResult = KgRequest.sendRequest();
if("0".toString().equals(requestResult.get("code"))) {
// 验签成功逻辑处理 ***// 这里做验证通过后的数据处理// 如登录/注册场景,这里通常查询数据库、校验密码、进行登录或注册等动作处理// 如短信场景,这里可以开始向用户发送短信等动作处理// ...
html = "<script>alert('验证通过');history.back();</script>";
} else {
// 验签失败逻辑处理
html = "<script>alert(\"" + requestResult.get("msg") + " - " + requestResult.get("code") + "\");history.back();</script>";
}
response.getWriter().append(html);
} else {
response.sendRedirect("index.html");
}
}
protectedvoiddoPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
doGet(request, response);
}
}
效果如下
![](https://img-blog.csdnimg.cn/img_convert/383ffb132e9dbc96cdf5e367bff37379.jpeg)
相关链接
官方地址:凯格行为验证码(KgCaptcha)滑动拼图验证,无感验证码,文字点选验证码
在线体验:凯格行为验证码在线体验
开发文档:凯格行为验证码-开发文档