Java ~ 常用验证码实现大全。
文章目录
Java 或 jQuery 实验验证码功能。
验证码(CAPTCHA)是“Completely Automated Public Turing test to tell Computers and Humans Apart”(全自动区分计算机和人类的图灵测试)的缩写,是一种区分用户是计算机还是人的公共全自动程序。可以防止:恶意破解密码、刷票、论坛灌水,有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试,实际上用验证码是现在很多网站通行的方式,我们利用比较简易的方式实现了这个功能。这个问题可以由计算机生成并评判,但是必须只有人类才能解答。由于计算机无法解答 CAPTCHA 的问题,所以回答出问题的用户就可以被认为是人类。
~
百科。
随机字符串验证码。
<%--
Created by IntelliJ IDEA.
User: geek
Date: 2020/5/13
Time: 17:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>随机验证码。</title>
<style type="text/css">
.code_a {
color: #0000ff;
font-size: 12px;
text-decoration: none;
cursor: pointer;
}
#imgCode {
cursor: pointer;
}
</style>
<script type="text/javascript">
function changeCode() {
var imgCode = document.getElementById("imgCode");
imgCode.src = "code21?" + Math.random();
}
</script>
</head>
<body>
<form action="/valiCodeServlet" method="post">
<label for="inCode">验证码:</label>
<input type="text" id="inCode" name="inCode">
<img src="code21" alt="" align="center" id="imgCode" onclick="changeCode()">
<a class="code_a" onclick="changeCode()">换一张</a><br>
<input type="submit" value="登录">
</form>
<div style="color: red;">${error}</div>
</body>
</html>
package com.geek.validCode;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
public class NewCode extends javax.servlet.http.HttpServlet {
private int width = 80;
private int height = 30;
private int fontSize = 15;
private String string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private Random random = new Random();
/**
* 生成 4 个字符的随机字符串。
*
* @return
*/
private String random4Code() {
String code = "";
for (int i = 0; i < 4; i++) {
code += string.charAt(random.nextInt(string.length()));
}
return code;
}
/**
* 生成至少 4 个字符的随机字符串。
*
* @return
*/
private String randomCodeGt4(int length) {
if (length < 4) {
length = 4;
}
// 更改宽度。
width = 5 + fontSize * length;
String code = "";
for (int i = 0; i < length; i++) {
code += string.charAt(random.nextInt(string.length()));
}
return code;
}
private Color randomColor() {
// 三原色最大值 255。(0~255)
int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
return new Color(r, g, b);
}
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
// 创建画板。
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 创建画笔。
Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
// 生成随机内容。
String code = random4Code();
request.getSession().setAttribute("valiCode", code);
// 绘制内容。
// 设置绘制区域。
graphics.fillRect(0, 0, width, height);
// 设置字体。
graphics.setFont(new Font("楷体", Font.BOLD, fontSize));
// 按顺序逐个绘制字符。
for (int i = 0; i < code.length(); i++) {
graphics.setColor(randomColor());
// 绘制字符。
graphics.drawString(code.charAt(i) + "", 5 + i * fontSize, (fontSize + height) / 2);
}
// 绘制噪音线。
for (int i = 0; i < 3; i++) {
graphics.setColor(randomColor());
graphics.setStroke(new BasicStroke(2));
graphics.drawLine(random.nextInt(width / 2), random.nextInt(height), random.nextInt(width), random.nextInt(height));
}
// 存为图片并发送。
ServletOutputStream outputStream = response.getOutputStream();
boolean png = ImageIO.write(bufferedImage, "png", outputStream);
outputStream.flush();
outputStream.close();
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
this.doPost(request, response);
}
}
package com.geek.validCode;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//@WebServlet(name = "/ValiCodeServlet")
public class ValiCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 得到数据。
String valiCode = request.getSession().getAttribute("valiCode").toString().toLowerCase();
String inCode = request.getParameter("inCode").toLowerCase();
// 验证是否正确。
if (inCode.equals(valiCode)) {
response.sendRedirect("index.jsp");
} else {
request.getSession().setAttribute("error", "验证码输入错误,请重新输入。");
// 返回上一页。
String referer = request.getHeader("Referer");
response.sendRedirect(referer);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>newCode</servlet-name>
<servlet-class>com.geek.validCode.NewCode</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>newCode</servlet-name>
<url-pattern>/code21</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>valiCodeServlet</servlet-name>
<servlet-class>com.geek.validCode.ValiCodeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>valiCodeServlet</servlet-name>
<url-pattern>/valiCodeServlet</url-pattern>
</servlet-mapping>
</web-app>
使用 JavaScript 实现随机字符串验证码。
减轻服务器压力。
纯 jQuery 验证码容易被破解。
var w = 80;
var h = 24;
var fontSize = h - 6;
var str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
// 随机生成最大值不超过 max 的整数。
function randInt(max) {
return Math.floor(Math.random() * 100000 % max);
}
// 生成随机长度的字符串验证码。
function randCode(length) {
if (length < 4) {
length = 4
}
var code = '';
for (var i = 0; i < length; i++) {
code += str.charAt(randInt(str.length));
}
return code;
}
// 生成随机颜色。
function randColor() {
var r = randInt(256);
var g = randInt(256);
var b = randInt(256);
return "rgb(" + r + "," + g + "," + b + ")";
}
// 生成图片。
function drawCode(canvas) {
var valicode = randCode(4);
w = 5 + fontSize * valicode.length;
if (canvas != null && canvas.getContext && canvas.getContext("2d")) {
// 设置显示区域大小。
canvas.style.width = w;
// 设置画板高度。
canvas.setAttribute("width", w);
canvas.setAttribute("height", h);
// 得到画笔。
var pen = canvas.getContext("2d");
// 绘制背景。
pen.fillStyle = "rgb(255, 255, 255)";
pen.fillRect(0, 0, w, h);
// 设置水平线位置。
pen.textBaseline = "top";// middle, bottom。
// 绘制内容。
for (var i = 0; i < valicode.length; i++) {
pen.fillStyle = randColor();
pen.font = "bold " + (fontSize + randInt(3)) + "px 楷体";
pen.fillText(valicode.charAt(i), 5 + fontSize * i, randInt(5));
}
// 绘制噪音线。
for (var i = 0; i < 2; i++) {
pen.moveTo(randInt(w) / 2, randInt(h));// 起点。
pen.lineTo(randInt(w), randInt(h));// 终点。
pen.strokeStyle = randColor();
pen.lineWidth = 2;
pen.stroke();
}
return valicode;
}
}
<%--
Created by IntelliJ IDEA.
User: geek
Date: 2020/5/13
Time: 17:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>随机验证码。</title>
<script src="js/validCode.js"></script>
<style type="text/css">
.code_a {
color: #0000ff;
font-size: 12px;
text-decoration: none;
cursor: pointer;
}
#cvs {
cursor: pointer;
}
</style>
<script type="text/javascript">
var valicode;
function changeCode() {
var cvs = document.getElementById("cvs");
valicode = drawCode(cvs);
}
function valiCode() {
var code = document.getElementById("inCode").value;
if (code.toLowerCase() == valicode.toLowerCase()) {
return true;
} else {
document.getElementById("err").innerHTML = "输入的验证码错误。";
changeCode();
return false;// 不提交页面。
}
}
window.onload = changeCode;
</script>
</head>
<body>
<form action="index.jsp" method="post">
<label for="inCode">验证码:</label>
<input type="text" id="inCode" name="inCode">
<%--<img src="code21" alt="" align="center" id="imgCode" onclick="changeCode()">--%>
<canvas id="cvs" onclick="changeCode()"></canvas>
<a class="code_a" onclick="changeCode()">换一张</a><br>
<input type="submit" value="登录" onclick="return valiCode()">
</form>
<div style="color: red;" id="err"></div>
</body>
</html>
算数验证码。
Java。
<%--
Created by IntelliJ IDEA.
User: geek
Date: 2020/5/13
Time: 17:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>随机验证码。</title>
<style type="text/css">
.code_a {
color: #0000ff;
font-size: 12px;
text-decoration: none;
cursor: pointer;
}
#imgCode {
cursor: pointer;
}
</style>
<script type="text/javascript">
function changeCode() {
var imgCode = document.getElementById("imgCode");
imgCode.src = "codeArithmetic?" + Math.random();
}
</script>
</head>
<body>
<form action="/valiCodeServletArithmetic" method="post">
<label for="inCode">验证码:</label>
<input type="text" id="inCode" name="inCode">
<img src="codeArithmetic" alt="" align="center" id="imgCode" onclick="changeCode()">
<a class="code_a" onclick="changeCode()">换一张</a><br>
<input type="submit" value="登录">
</form>
<div style="color: red;">${error}</div>
</body>
</html>
package com.geek.arithmeticCode;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
/**
* 算术验证码。
*/
//@WebServlet(name = "NewCodeServlet")
public class NewCodeServlet extends HttpServlet {
private int width = 140;
private int height = 30;
private int fontSize = 18;
private String string = "+-*/";
private int result = -1;// 保存计算结果。
private Random random = new Random();
/**
* 生成 4 个字符的随机字符串。
*
* @return
*/
private String randomCode() {
int one = random.nextInt(100);
int two = random.nextInt(100);
char op = string.charAt(random.nextInt(string.length()));
switch (op) {
case '+':
result = one + two;
break;
case '-':
result = one - two;
break;
case '*':
result = one * two;
break;
case '/':
result = one / two;
break;
}
return "" + one + " " + op + " " + two + " = ?";
}
private Color randColor() {
// 三原色最大值 255。(0~255)
int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
return new Color(r, g, b);
}
/**
* 生成至少 4 个字符的随机字符串。
*
* @return
*/
private String randomCodeGt4(int length) {
if (length < 4) {
length = 4;
}
// 更改宽度。
width = 5 + fontSize * length;
String code = "";
for (int i = 0; i < length; i++) {
code += string.charAt(random.nextInt(string.length()));
}
return code;
}
private Color randomColor() {
// 三原色最大值 255。(0~255)
int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
return new Color(r, g, b);
}
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
// 创建画板。
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 创建画笔。
Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
// 生成随机内容。
String code = randomCode();
request.getSession().setAttribute("valiCode", result);
// 绘制内容。
// 设置绘制区域。
graphics.fillRect(0, 0, width, height);
// 设置字体。
graphics.setFont(new Font("楷体", Font.BOLD, fontSize));
// 按顺序逐个绘制字符。
for (int i = 0; i < code.length(); i++) {
graphics.setColor(randomColor());
// 绘制字符。
graphics.drawString(code.charAt(i) + "", 5 + i * fontSize, (fontSize + height) / 2);
}
// 绘制噪音线。
for (int i = 0; i < 3; i++) {
graphics.setColor(randomColor());
graphics.setStroke(new BasicStroke(2));
graphics.drawLine(random.nextInt(width / 2), random.nextInt(height), random.nextInt(width), random.nextInt(height));
}
// 存为图片并发送。
ServletOutputStream outputStream = response.getOutputStream();
boolean png = ImageIO.write(bufferedImage, "png", outputStream);
outputStream.flush();
outputStream.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
package com.geek.arithmeticCode;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//@WebServlet(name = "ValiCodeServlet")
public class ValiCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 得到数据。
String valiCode = request.getSession().getAttribute("valiCode").toString().toLowerCase();
String inCode = request.getParameter("inCode").toLowerCase();
// 验证是否正确。
if (inCode.equals(valiCode)) {
response.sendRedirect("index.jsp");
} else {
request.getSession().setAttribute("error", "验证码输入错误,请重新输入。");
// 返回上一页。
String referer = request.getHeader("Referer");
response.sendRedirect(referer);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
JavaScript。
- validCode_javascript.js。
var w = 80;
var h = 24;
var fontSize = h - 6;
var str = "+-*";
// 随机生成最大值不超过 max 的整数。
function randInt(max) {
return Math.floor(Math.random() * 100000 % max);
}
// 生成随机长度的字符串验证码。
function randCode(length) {
var one = randInt(100);
var two = randInt(100);
var op = str.charAt(randInt(str.length));
return "" + one + op + two + "=";
}
// 生成随机颜色。
function randColor() {
var r = randInt(256);
var g = randInt(256);
var b = randInt(256);
return "rgb(" + r + "," + g + "," + b + ")";
}
// 生成图片。
function drawCode(canvas) {
var valicode = randCode();
w = 5 + fontSize * valicode.length;
if (canvas != null && canvas.getContext && canvas.getContext("2d")) {
// 设置显示区域大小。
canvas.style.width = w;
// 设置画板高度。
canvas.setAttribute("width", w);
canvas.setAttribute("height", h);
// 得到画笔。
var pen = canvas.getContext("2d");
// 绘制背景。
pen.fillStyle = "rgb(255, 255, 255)";
pen.fillRect(0, 0, w, h);
// 设置水平线位置。
pen.textBaseline = "top";// middle, bottom。
// 绘制内容。
for (var i = 0; i < valicode.length; i++) {
pen.fillStyle = randColor();
pen.font = "bold " + (fontSize + randInt(3)) + "px 楷体";
pen.fillText(valicode.charAt(i), 5 + fontSize * i, randInt(5));
}
// 绘制噪音线。
for (var i = 0; i < 2; i++) {
pen.moveTo(randInt(w) / 2, randInt(h));// 起点。
pen.lineTo(randInt(w), randInt(h));// 终点。
pen.strokeStyle = randColor();
pen.lineWidth = 2;
pen.stroke();
}
valicode = valicode.substr(0, valicode.length - 1);
// eval 函数。把字符串当表达式处理。
return eval(valicode);
}
}
- login_arithmeic_javascript.jsp。
<%--
Created by IntelliJ IDEA.
User: geek
Date: 2020/5/13
Time: 17:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>随机验证码。</title>
<script src="js/validCode_javascript.js"></script>
<style type="text/css">
.code_a {
color: #0000ff;
font-size: 12px;
text-decoration: none;
cursor: pointer;
}
#cvs {
cursor: pointer;
}
</style>
<script type="text/javascript">
var valicode;
function changeCode() {
var cvs = document.getElementById("cvs");
valicode = drawCode(cvs);
}
function valiCode() {
var code = document.getElementById("inCode").value;
if (code.toString() == valicode.toString()) {
return true;
} else {
document.getElementById("err").innerHTML = "输入的验证码错误。";
changeCode();
return false;// 不提交页面。
}
}
window.onload = changeCode;
</script>
</head>
<body>
<form action="index.jsp" method="post">
<label for="inCode">验证码:</label>
<input type="text" id="inCode" name="inCode">
<%--<img src="code21" alt="" align="center" id="imgCode" onclick="changeCode()">--%>
<canvas id="cvs" onclick="changeCode()"></canvas>
<a class="code_a" onclick="changeCode()">换一张</a><br>
<input type="submit" value="登录" onclick="return valiCode()">
</form>
<div style="color: red;" id="err"></div>
</body>
</html>
使用 kaptcha 框架实现验证码~配置。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.geek</groupId>
<artifactId>kaptcha-geek</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
</dependencies>
</project>
- web.xml。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>kaptchaServlet</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>kaptchaServlet</servlet-name>
<url-pattern>/ks</url-pattern>
</servlet-mapping>
</web-app>
常用配置。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>kaptchaServlet</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
<!-- 属性。-->
<init-param>
<param-name>kaptcha.border</param-name>
<param-value>no</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.font.color</param-name>
<param-value>red</param-value>
</init-param>
<init-param>
<param-name>kaptcha.image.width</param-name>
<param-value>80</param-value>
</init-param>
<init-param>
<param-name>kaptcha.image.height</param-name>
<param-value>30</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.char.string</param-name>
<param-value>0123456789</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.char.length</param-name>
<param-value>4</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.char.space</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.font.size</param-name>
<param-value>24</param-value>
</init-param>
<init-param>
<param-name>kaptcha.obscurificator.impl</param-name>
<param-value>com.google.code.kaptcha.impl.FishEyeGimpy</param-value>
</init-param>
<init-param>
<param-name>kaptcha.noise.impl</param-name>
<param-value>com.google.code.kaptcha.impl.NoNoise</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>kaptchaServlet</servlet-name>
<url-pattern>/ks</url-pattern>
</servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>valiCodeServlet</servlet-name>
<servlet-class>com.geek.ValiCodeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>valiCodeServlet</servlet-name>
<url-pattern>/vcs</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>kaptchaServlet</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
<!-- 属性。-->
<init-param>
<param-name>kaptcha.border</param-name>
<param-value>no</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.font.color</param-name>
<param-value>red</param-value>
</init-param>
<init-param>
<param-name>kaptcha.image.width</param-name>
<param-value>80</param-value>
</init-param>
<init-param>
<param-name>kaptcha.image.height</param-name>
<param-value>30</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.char.string</param-name>
<param-value>0123456789</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.char.length</param-name>
<param-value>4</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.char.space</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.font.size</param-name>
<param-value>24</param-value>
</init-param>
<!--<init-param>-->
<!--<param-name>kaptcha.obscurificator.impl</param-name>-->
<!--<param-value>com.google.code.kaptcha.impl.FishEyeGimpy</param-value>-->
<!--</init-param>-->
<init-param>
<param-name>kaptcha.noise.impl</param-name>
<param-value>com.google.code.kaptcha.impl.NoNoise</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>kaptchaServlet</servlet-name>
<url-pattern>/ks</url-pattern>
</servlet-mapping>
</web-app>
package com.geek;
import com.google.code.kaptcha.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//@WebServlet(name = "ValiCodeServlet")
public class ValiCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String valiCode = request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY).toString().toLowerCase();
String inCode = request.getParameter("inCode").toLowerCase();
if (inCode.equals(valiCode)) {
response.sendRedirect("index.jsp");
} else {
request.getSession().setAttribute("err", "验证码输入错误。");
String url = request.getHeader("Referer");
response.sendRedirect(url);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
使用 kaptcha 框架实现验证码~代码。
package com.geek.kaptcha;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Properties;
public class NewCode extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req, resp);
// 设置属性集。
Properties properties = new Properties();
properties.put("kaptcha.border", "no");
properties.put("kaptcha.textproducer.font.color", "red");
properties.put("kaptcha.image.width", "80");
properties.put("kaptcha.image.height", "30");
properties.put("kaptcha.textproducer.char.string", "0123456789");
properties.put("kaptcha.textproducer.char.length", "4");
properties.put("kaptcha.textproducer.char.space", "5");
properties.put("kaptcha.textproducer.font.size", "25");
properties.put("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");
properties.put("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.FishEyeGimpy");
Config config = new Config(properties);
// 创建 kaptcha 对象。
DefaultKaptcha kaptcha = new DefaultKaptcha();
kaptcha.setConfig(config);
// 生成验证码并保存到 session。
String code = kaptcha.createText();
req.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, code);
// 生成图片。
BufferedImage image = kaptcha.createImage(code);
// 返回图片。
ServletOutputStream outputStream = resp.getOutputStream();
ImageIO.write(image, "png", outputStream);
outputStream.flush();
outputStream.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
this.doGet(req, resp);
}
}
package com.geek.kaptcha;
import com.google.code.kaptcha.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//@WebServlet(name = "ValiCodeServlet")
public class ValiCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String valiCode = request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY).toString().toLowerCase();
String inCode = request.getParameter("inCode").toLowerCase();
if (inCode.equals(valiCode)) {
response.sendRedirect("index.jsp");
} else {
request.getSession().setAttribute("err", "验证码输入错误。");
String url = request.getHeader("Referer");
response.sendRedirect(url);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>随机验证码。</title>
<style type="text/css">
.code_a {
color: #0000ff;
font-size: 12px;
text-decoration: none;
cursor: pointer;
}
#imgCode {
cursor: pointer;
}
</style>
<script type="text/javascript">
function changeCode() {
var imgCode = document.getElementById("imgCode");
imgCode.src = "nc?" + Math.random();
}
</script>
</head>
<body>
<form action="/vcs_java" method="post">
<label for="inCode">验证码:</label>
<input type="text" id="inCode" name="inCode">
<img src="nc" alt="" align="center" id="imgCode" onclick="changeCode()">
<a class="code_a" onclick="changeCode()">换一张</a><br>
<input type="submit" value="登录">
</form>
<div style="color: red;">${err}</div>
</body>
</html>
滑块验证码。
jQuery。
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
aliyun。
安全云盾~数据风控(业务安全)。
人机验证产品
基于阿里大数据计算能力,通过业内领先的风险决策引擎,解决企业账号、活动、交易等关键业务缓解存在的欺诈威胁。
- demo 代码。应用代码集成。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<!-- 国内使用 -->
<script type="text/javascript" charset="utf-8" src="//g.alicdn.com/sd/ncpc/nc.js?t=2015052012"></script>
<!-- 若您的主要用户来源于海外,请替换使用下面的js资源 -->
<!-- <script type="text/javascript" charset="utf-8" src="//aeis.alicdn.com/sd/ncpc/nc.js?t=2015052012"></script> -->
</head>
<body>
<div id="your-dom-id" class="nc-container"></div> <!--No-Captcha渲染的位置,其中 class 中必须包含 nc-container-->
<script type="text/javascript">
var nc_token = ["FFFF0N00000000009112", (new Date()).getTime(), Math.random()].join(':');
var NC_Opt =
{
renderTo: "#your-dom-id",
appkey: "FFFF0N00000000009112",
scene: "nc_login",
token: nc_token,
customWidth: 300,
trans:{"key1":"code0"},
elementID: ["usernameID"],
is_Opt: 0,
language: "cn",
isEnabled: true,
timeout: 3000,
times:5,
apimap: {
// 'analyze': '//a.com/nocaptcha/analyze.jsonp',
// 'get_captcha': '//b.com/get_captcha/ver3',
// 'get_captcha': '//pin3.aliyun.com/get_captcha/ver3'
// 'get_img': '//c.com/get_img',
// 'checkcode': '//d.com/captcha/checkcode.jsonp',
// 'umid_Url': '//e.com/security/umscript/3.2.1/um.js',
// 'uab_Url': '//aeu.alicdn.com/js/uac/909.js',
// 'umid_serUrl': 'https://g.com/service/um.json'
},
callback: function (data) {
window.console && console.log(nc_token)
window.console && console.log(data.csessionid)
window.console && console.log(data.sig)
}
}
var nc = new noCaptcha(NC_Opt)
nc.upLang('cn', {
_startTEXT: "请按住滑块,拖动到最右边",
_yesTEXT: "验证通过",
_error300: "哎呀,出错了,点击<a href=\"javascript:__nc.reset()\">刷新</a>再来一次",
_errorNetwork: "网络不给力,请<a href=\"javascript:__nc.reset()\">点击刷新</a>",
})
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script src="js/jquery-3.5.1.min.js" type="text/javascript" charset="UTF-8"></script>
<!-- 国内使用 -->
<script type="text/javascript" charset="utf-8" src="//g.alicdn.com/sd/ncpc/nc.js?t=2015052012"></script>
<!-- 若您的主要用户来源于海外,请替换使用下面的js资源 -->
<!-- <script type="text/javascript" charset="utf-8" src="//aeis.alicdn.com/sd/ncpc/nc.js?t=2015052012"></script> -->
<style>
#btnOK {
border: none;
color: white;
text-align: center;
display: inline-block;
font-size: 16px;
}
</style>
</head>
<body>
<form action="index.jsp" method="post">
<div>
<label>验证:</label>
<div id="your-dom-id" class="nc-container"></div> <!--No-Captcha渲染的位置,其中 class 中必须包含 nc-container-->
<input type="submit" value="登录" id="btnOK" disabled="disabled">
</div>
</form>
<!--<div id="your-dom-id" class="nc-container"></div> <!–No-Captcha渲染的位置,其中 class 中必须包含 nc-container–>-->
<script type="text/javascript">
var nc_token = ["FFFF0N00000000009112", (new Date()).getTime(), Math.random()].join(':');
var NC_Opt =
{
renderTo: "#your-dom-id",
appkey: "FFFF0N00000000009112",
scene: "nc_login",
token: nc_token,
customWidth: 300,
trans: {"key1": "code0"},
elementID: ["usernameID"],
is_Opt: 0,
language: "cn",
isEnabled: true,
timeout: 3000,
times: 5,
apimap: {
// 'analyze': '//a.com/nocaptcha/analyze.jsonp',
// 'get_captcha': '//b.com/get_captcha/ver3',
// 'get_captcha': '//pin3.aliyun.com/get_captcha/ver3'
// 'get_img': '//c.com/get_img',
// 'checkcode': '//d.com/captcha/checkcode.jsonp',
// 'umid_Url': '//e.com/security/umscript/3.2.1/um.js',
// 'uab_Url': '//aeu.alicdn.com/js/uac/909.js',
// 'umid_serUrl': 'https://g.com/service/um.json'
},
callback: function (data) {
$("#btnOK").prop("disabled", "");
$("#btnOK").css("background-color", "green")
// window.console && console.log(nc_token)
// window.console && console.log(data.csessionid)
// window.console && console.log(data.sig)
}
};
var nc = new noCaptcha(NC_Opt)
nc.upLang('cn', {
_startTEXT: "请按住滑块,拖动到最右边",
_yesTEXT: "验证通过",
_error300: "哎呀,出错了,点击<a href=\"javascript:__nc.reset()\">刷新</a>再来一次",
_errorNetwork: "网络不给力,请<a href=\"javascript:__nc.reset()\">点击刷新</a>",
})
</script>
</body>
</html>
图形验证码。
jQuery。
WebAPI~腾讯。
tencent waterproof wall。腾讯防水墙。
https://007.qq.com/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>腾讯验证框架。</title>
<script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
<script src="js/jquery-3.5.1.min.js"></script>
<script>
function vali() {
// var valicode = new TencentCaptcha(appId, callback, options);
var appId = 'appId';// 填写申请的 appId。
var valicode = new TencentCaptcha(appId, function (res) {
if (res.ret == 0) {
// 成功。
var form = document.getElementById("form1");
form.submit();
} else {
alert("验证出错。")
}
});
valicode.show();
}
</script>
</head>
<body>
<form action="index.jsp" id="form1" method="post">
<div>
<input type="button" value="登录" id="btnOK" onclick="vali()">
</div>
</form>
</body>
</html>
手机短信验证码。
https://user.ihuyi.com/index.html
<%@ page language="java" pageEncoding="utf-8" %>
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>demo</title>
</head>
<script type="text/javascript" src="js/jquery-3.5.1.min.js"></script>
<script language="javascript">
function get_mobile_code() {
// $.post('sms.jsp', {mobile: jQuery.trim($('#mobile').val()), send_code: $("#gd_code").val()}, function (msg) {
$.post('/sms', {mobile: jQuery.trim($('#mobile').val())}, function (msg) {
alert(jQuery.trim(unescape(msg)));
if (msg.indexOf('提交成功')) {
RemainTime();
$("#err").text("");
} else {
// location.reload();
$("#err").text("验证码错误。");
}
});
}
var iTime = 59;
var Account;
function RemainTime() {
document.getElementById('zphone').disabled = true;
var iSecond, sSecond = "", sTime = "";
if (iTime >= 0) {
iSecond = parseInt(iTime % 60);
iMinute = parseInt(iTime / 60);
if (iSecond >= 0) {
if (iMinute > 0) {
sSecond = iMinute + "分" + iSecond + "秒";
} else {
sSecond = iSecond + "秒";
}
}
sTime = sSecond;
if (iTime == 0) {
clearTimeout(Account);
sTime = '获取手机验证码';
iTime = 59;
document.getElementById('zphone').disabled = false;
} else {
Account = setTimeout("RemainTime()", 1000);
iTime = iTime - 1;
}
} else {
sTime = '没有倒计时';
}
document.getElementById('zphone').value = sTime;
}
</script>
<body>
<form action="vc7" method="post" name="formUser" onSubmit="return register();">
<table width="100%" border="0" align="left" cellpadding="5" cellspacing="3">
<tr>
<td align="right">手机</td>
<td align="left">
<input id="mobile" name="mobile" type="text" size="25" class="inputBg"/><span
style="color:#FF0000"> *</span>
</td>
</tr>
<%--
<tr>
<td align="right">验证码</td>
<td>
<input type="text" name="gd_code" class="inputBg" size="25" id="gd_code"
onkeyup="value=value.replace(/[^\d]/g,'')" placeholder="请输入正确的验证码">
<span> <img src="code.jsp" onClick="javascript:this.src=this.src+'?date='+Date();"></span>
</td>
</tr>
--%>
<tr>
<td align="right">手机验证码</td>
<td align="left">
<input type="text" id="mobile_code" name="mobile_code" class="inputBg" size="25"/>
<input id="zphone" type="button" value=" 获取手机验证码 " style="width: 120px" onClick="get_mobile_code()">
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="登录" id="btnOK">
</td>
</tr>
<tr>
<td></td>
<td>
<div id="err" style="color: red;">${err}</div>
</td>
</tr>
</table>
</form>
</body>
</html>
package com.geek.ihuyi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
@javax.servlet.annotation.WebServlet(name = "/sms")
public class SMSCodeServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
// 接口类型:互亿无线触发短信接口,支持发送验证码短信、订单通知短信等。
// 账户注册:请通过该地址开通账户 http://sms.ihuyi.com/register.html
// 注意事项:
//(1)调试期间,请使用用系统默认的短信内容:您的验证码是:【变量】。请不要把验证码泄露给其他人。
//(2)请使用APIID(查看APIID请登录用户中心->验证码短信->产品总览->APIID)及 APIkey 来调用接口。
//(3)该代码仅供接入互亿无线短信接口参考使用,客户可根据实际需要自行编写。
String postUrl = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
int mobile_code = (int) ((Math.random() * 9 + 1) * 100000);// 获取随机数。
// ~ ~ ~
request.getSession().setAttribute("valiCode", mobile_code);
// ~ ~ ~
String account = "";// 查看用户名是登录用户中心->验证码短信->产品总览->APIID
String password = "";// 查看密码请登录用户中心->验证码短信->产品总览->APIKEY
String mobile = request.getParameter("mobile");
String content = new String("您的验证码是:" + mobile_code + "。请不要把验证码泄露给其他人。");
/* String send_code = request.getParameter("send_code");
String session_code = (String) session.getAttribute("randStr");
// 此处验证码仅限于纯数字比对。
if (Integer.parseInt(send_code) != Integer.valueOf(session_code)) {
String message = new String("请输入正确的验证码");
out.println(message);
return;
}*/
try {
URL url = new URL(postUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);// 允许连接提交信息。
connection.setRequestMethod("POST");// 网页提交方式“GET”、“POST”。
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Connection", "Keep-Alive");
StringBuffer sb = new StringBuffer();
sb.append("account=" + account);
sb.append("&password=" + password);
sb.append("&mobile=" + mobile);
sb.append("&content=" + content);
OutputStream os = connection.getOutputStream();
os.write(sb.toString().getBytes());
os.close();
String line, result = "";
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
while ((line = in.readLine()) != null) {
result += line + "\n";
}
in.close();
response.setCharacterEncoding("utf-8");
response.getWriter().write(result);
// out.println(result);
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
this.doPost(request, response);
}
}
package com.geek.ihuyi;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//@WebServlet(name = "/vc7")
public class ValicodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 得到数据。
String inCode = request.getParameter("mobile_code").toLowerCase();
String valiCode = request.getSession().getAttribute("valiCode").toString().toLowerCase();
// 验证。
if (inCode.equals(valiCode)) {
response.sendRedirect("index.jsp");
} else {
request.getSession().setAttribute("err", "验证码错误。");
String referer = request.getHeader("Referer");
response.sendRedirect(referer);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}