Java如何實現(xiàn)kaptcha網(wǎng)頁驗證碼驗證
Java實現(xiàn)kaptcha網(wǎng)頁驗證碼驗證
首先來了解一下什么是驗證碼:
- 驗證碼(CAPTCHA) ∶是一種區(qū)分用戶是計算機還是人的公共全自動程序。
- 作用∶可以防止惡意破解密碼、刷票、論壇灌水,有效防止某個黑客對某一個特定注冊用戶用特定程序暴力破解方式進行不斷的登陸嘗試。實際上用驗證碼是現(xiàn)在很多網(wǎng)站通行的方式(比如招商銀行的網(wǎng)上個人銀行,百度社區(qū)),我們利用比較簡易的方式實現(xiàn)了這個功能。
下面便一起來了解kaptcha吧
首先要了解什么是kaptcha?
- 它一個java開源的驗證碼工具包,kaptcha 是一個非常實用的驗證碼生成工具,可以通過配置生成多樣化的驗證碼。
- 當(dāng)然除了kaptcha可以實現(xiàn)驗證碼外,還可以通過servlet、jcaptcha來實現(xiàn)驗證碼。
kaptcha工作的原理:
- 調(diào)用 com.google.code.kaptcha.servlet.KaptchaServlet,生成一個圖片。
- 同時將生成的驗證碼字符串放到 HttpSession中。
相關(guān)文章:
SpringBoot整合kaptcha驗證碼,復(fù)制粘貼即可用
我的項目目錄:

一、引入Maven依賴
pom.xml:
<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha --> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
二、編寫Servlet
kaptcha可配置項參考:
kaptcha.border --------------------------------------------------是否有邊框 默認為true 我們可以自己設(shè)置yes,no
kaptcha.border.color -------------------------------------------邊框顏色 默認為Color.BLACK
kaptcha.border.thickness -------------------------------------邊框粗細度 默認為1
kaptcha.producer.impl -----------------------------------------驗證碼生成器 默認為DefaultKaptcha
kaptcha.textproducer.impl ------------------------------------驗證碼文本生成器 默認為DefaultTextCreator
kaptcha.textproducer.char.string ----------------------------驗證碼文本字符內(nèi)容范圍 默認為abcde2345678gfynmnpwx
kaptcha.textproducer.char.length ---------------------------驗證碼文本字符長度 默認為5
kaptcha.textproducer.font.names ---------------------------驗證碼文本字體樣式 默認為new Font(“Arial”, 1, fontSize), new Font(“Courier”, 1, fontSize)
kaptcha.textproducer.font.size ------------------------------驗證碼文本字符大小 默認為40
kaptcha.textproducer.font.color -----------------------------驗證碼文本字符顏色 默認為Color.BLACK
kaptcha.textproducer.char.space -------------------------- 驗證碼文本字符間距 默認為2
kaptcha.noise.impl ----------------------------------------------驗證碼噪點生成對象 默認為DefaultNoise
kaptcha.noise.color ---------------------------------------------驗證碼噪點顏色 默認為Color.BLACK
kaptcha.obscurificator.impl ------------------------------------驗證碼樣式引擎 默認為WaterRipple
kaptcha.word.impl -----------------------------------------------驗證碼文本字符渲染 默認為DefaultWordRenderer
kaptcha.background.impl --------------------------------------驗證碼背景生成器 默認為DefaultBackground
kaptcha.background.clear.from ------------------------------驗證碼背景顏色漸進 默認為Color.LIGHT_GRAY
kaptcha.background.clear.to ----------------------------------驗證碼背景顏色漸進 默認為Color.WHITE
kaptcha.image.width --------------------------------------------驗證碼圖片寬度 默認為200
kaptcha.image.height -------------------------------------------驗證碼圖片高度 默認為50
在web.xml文件中配置kaptcha與它的servlet映射等。
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <!-- 登陸驗證碼Kaptcha 2--> <servlet> <servlet-name>Kaptcha</servlet-name> <servlet-class> com.google.code.kaptcha.servlet.KaptchaServlet </servlet-class> <init-param> <description>圖片邊框,合法值:yes , no</description> <param-name>kaptcha.border</param-name> <param-value>yes</param-value> </init-param> <init-param> <description> 邊框顏色,合法值: r,g,b (and optional alpha) 或者 white,black,blue. </description> <param-name>kaptcha.border.color</param-name> <param-value>black</param-value> </init-param> <init-param> <description>邊框厚度,合法值:>0</description> <param-name>kaptcha.border.thickness</param-name> <param-value>1</param-value> </init-param> <init-param> <description>圖片寬 200</description> <param-name>kaptcha.image.width</param-name> <param-value>200</param-value> </init-param> <init-param> <description>圖片高 50</description> <param-name>kaptcha.image.height</param-name> <param-value>50</param-value> </init-param> <init-param> <description>圖片實現(xiàn)類</description> <param-name>kaptcha.producer.impl</param-name> <param-value> com.google.code.kaptcha.impl.DefaultKaptcha </param-value> </init-param> <init-param> <description>文本實現(xiàn)類</description> <param-name>kaptcha.textproducer.impl</param-name> <param-value> com.google.code.kaptcha.text.impl.DefaultTextCreator </param-value> </init-param> <init-param> <description>文本集合,驗證碼值從此集合中獲取</description> <param-name>kaptcha.textproducer.char.string</param-name> <param-value>1234567890</param-value> <!--<param-value>abcde2345678gfynmnpwx</param-value>--> </init-param> <init-param> <description>驗證碼長度 5</description> <param-name>kaptcha.textproducer.char.length</param-name> <param-value>5</param-value> </init-param> <init-param> <description>字體 Arial, Courier</description> <param-name>kaptcha.textproducer.font.names</param-name> <param-value>Arial, Courier</param-value> </init-param> <init-param> <description>字體大小 40px.</description> <param-name>kaptcha.textproducer.font.size</param-name> <param-value>40</param-value> </init-param> <init-param> <description> 字體顏色,合法值: r,g,b 或者 white,black,blue. </description> <param-name>kaptcha.textproducer.font.color</param-name> <param-value>black</param-value> </init-param> <init-param> <description>文字間隔 2</description> <param-name>kaptcha.textproducer.char.space</param-name> <param-value>2</param-value> </init-param> <init-param> <description>干擾實現(xiàn)類</description> <param-name>kaptcha.noise.impl</param-name> <param-value> <!-- com.google.code.kaptcha.impl.NoNoise --> com.google.code.kaptcha.impl.DefaultNoise </param-value> </init-param> <init-param> <description> 干擾顏色,合法值: r,g,b 或者 white,black,blue. </description> <param-name>kaptcha.noise.color</param-name> <param-value>black</param-value> </init-param> <init-param> <description> 圖片樣式: 水紋com.google.code.kaptcha.impl.WaterRipple 魚眼com.google.code.kaptcha.impl.FishEyeGimpy 陰影com.google.code.kaptcha.impl.ShadowGimpy </description> <param-name>kaptcha.obscurificator.impl</param-name> <param-value> com.google.code.kaptcha.impl.WaterRipple </param-value> </init-param> <init-param> <description>背景實現(xiàn)類</description> <param-name>kaptcha.background.impl</param-name> <param-value> com.google.code.kaptcha.impl.DefaultBackground </param-value> </init-param> <init-param> <description>背景顏色漸變,開始顏色</description> <param-name>kaptcha.background.clear.from</param-name> <param-value> black</param-value> </init-param> <init-param> <description>背景顏色漸變,結(jié)束顏色</description> <param-name>kaptcha.background.clear.to</param-name> <param-value>white</param-value> </init-param> <init-param> <description>文字渲染器</description> <param-name>kaptcha.word.impl</param-name> <param-value> com.google.code.kaptcha.text.impl.DefaultWordRenderer </param-value> </init-param> <init-param> <description> session中存放驗證碼的key鍵 </description> <param-name>kaptcha.session.key</param-name> <param-value>KAPTCHA_SESSION_KEY</param-value> </init-param> <init-param> <description> 生成kaptcha的日期被放入HttpSession中。這是會話中該項的鍵值。 </description> <param-name>kaptcha.session.date</param-name> <param-value>KAPTCHA_SESSION_DATE</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Kaptcha</servlet-name> <url-pattern>/randomcode.jpg</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
三、編寫:頁面、判斷與跳轉(zhuǎn)
1、只有數(shù)字的驗證碼
index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>randomcode</title>
<script type="text/javascript">
function changeR(node){
// 用于點擊時產(chǎn)生不同的驗證碼
node.src = "randomcode.jpg?time="+new Date().getTime() ;
}
</script>
</head>
<body>
<img alt="random" src="randomcode.jpg" onclick="changeR(this)" style="cursor: pointer;">
<form action="check.jsp">
<input type="text" name="r">
<input type="submit" value="確認">
</form>
</body>
</html>check.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>check</title>
</head>
<body>
<%
// 檢查是否是正確的驗證碼
String k = (String) session
.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
String str = request.getParameter("r");
str = new String(str.getBytes("iso-8859-1"),"utf-8");
if (k.equals(str))
out.print("輸入驗證碼正確!");
else
out.print("輸入驗證碼錯誤?。?!");
out.print("驗證碼為:" + k + ",你輸入的驗證碼為:" + str);
%>
</body>
</html>結(jié)果為:


2、含義數(shù)字、字母、中文的驗證碼
以上便是數(shù)字驗證碼,那如果加字母和中文 呢???
更改web.xml的文本實現(xiàn)類,導(dǎo)入自己創(chuàng)建的類:
我的web.xml的引入和我類的位置:(自行尋找到進行更換)
<init-param> <description>文本實現(xiàn)類</description> <param-name>kaptcha.textproducer.impl</param-name> <param-value> com.kaptcha.ChineseText </param-value> </init-param>
ChineseText.java:
package com.kaptcha;
import java.util.Random;
import com.google.code.kaptcha.text.TextProducer;
import com.google.code.kaptcha.util.Configurable;
public class ChineseText extends Configurable implements TextProducer {
public String getText() {
int length = getConfig().getTextProducerCharLength();
String finalWord = "", firstWord = "";
int tempInt = 0;
String[] array = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"a", "b", "c", "d", "e", "f","g", "h", "i", "j", "k"};
Random rand = new Random();
for (int i = 0; i < length; i++) {
switch (rand.nextInt(array.length)) {
case 1:
tempInt = rand.nextInt(26) + 65;
firstWord = String.valueOf((char) tempInt);
break;
case 2:
int r1,
r2,
r3,
r4;
String strH,
strL; // high&low
r1 = rand.nextInt(3) + 11;
if (r1 == 13) {
r2 = rand.nextInt(7);
} else {
r2 = rand.nextInt(16);
}
r3 = rand.nextInt(6) + 10;
if (r3 == 10) {
r4 = rand.nextInt(15) + 1;
} else if (r3 == 15) {
r4 = rand.nextInt(15);
} else {
r4 = rand.nextInt(16);
}
strH = array[r1] + array[r2];
strL = array[r3] + array[r4];
byte[] bytes = new byte[2];
bytes[0] = (byte) (Integer.parseInt(strH, 16));
bytes[1] = (byte) (Integer.parseInt(strL, 16));
firstWord = new String(bytes);
break;
default:
tempInt = rand.nextInt(10) + 48;
firstWord = String.valueOf((char) tempInt);
break;
}
finalWord += firstWord;
}
return finalWord;
}
}這個的效果:


3、兩個數(shù)相加的驗證碼
運行都是OK的,學(xué)到這里那兩個數(shù)的算式驗證碼應(yīng)該如何實現(xiàn)呢???
首先,我們就要更改servlet里的kaptcha的默認的KaptchaServlet,自己在寫一個,還有就是我們的是兩個數(shù)的算法,那也就要更改驗證碼長度的長度,還有更改我們上面實現(xiàn)的中文和字母換回默認值。
先更改一下web.xml:(自行尋找進行更換)
<servlet-class> com.kaptcha.KaptchaServlet </servlet-class>
<init-param> <description>文本實現(xiàn)類</description> <param-name>kaptcha.textproducer.impl</param-name> <param-value> com.google.code.kaptcha.text.impl.DefaultTextCreator </param-value> </init-param>
<init-param> <description>驗證碼長度 2</description> <param-name>kaptcha.textproducer.char.length</param-name> <param-value>2</param-value> </init-param>
KaptchaServlet.java:
package com.kaptcha;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;
import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
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.Enumeration;
import java.util.Properties;
public class KaptchaServlet extends HttpServlet implements Servlet {
private Properties props;
private Producer kaptchaProducer;
private String sessionKeyValue;
public KaptchaServlet() {
this.props = new Properties();
this.kaptchaProducer = null;
this.sessionKeyValue = null;
}
public void init(ServletConfig conf) throws ServletException {
super.init(conf);
ImageIO.setUseCache(false);
Enumeration initParams = conf.getInitParameterNames();
while (initParams.hasMoreElements()) {
String key = (String) initParams.nextElement();
String value = conf.getInitParameter(key);
this.props.put(key, value);
}
Config config = new Config(this.props);
this.kaptchaProducer = config.getProducerImpl();
this.sessionKeyValue = config.getSessionKey();
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setDateHeader("Expires", 0L);
resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
resp.setHeader("Pragma", "no-cache");
resp.setContentType("image/jpeg");
String capText = this.kaptchaProducer.createText();
String s1 = capText.substring(0, 1);
String s2 = capText.substring(1, 2);
int r = Integer.valueOf(s1).intValue() + Integer.valueOf(s2).intValue();
req.getSession().setAttribute(this.sessionKeyValue, String.valueOf(r));
BufferedImage bi = this.kaptchaProducer.createImage(s1+"+"+s2+"=?");
ServletOutputStream out = resp.getOutputStream();
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
}
}效果為:


總結(jié)
以上便是比較簡單的java實現(xiàn)驗證碼的操作
這些僅為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
MyBatis之自查詢使用遞歸實現(xiàn) N級聯(lián)動效果(兩種實現(xiàn)方式)
這篇文章主要介紹了MyBatis之自查詢使用遞歸實現(xiàn) N級聯(lián)動效果,本文給大家分享兩種實現(xiàn)方式,需要的的朋友參考下吧2017-07-07
java?Comparable和Comparator的區(qū)別及作用面試精講
這篇文章主要為大家介紹了java?Comparable和Comparator的區(qū)別及作用面試精講,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10
GraalVM系列Native?Image?Basics靜態(tài)分析
這篇文章主要為大家介紹了GraalVM系列Native?Image?Basics靜態(tài)分析詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02
Spring?JPA使用CriteriaBuilder動態(tài)構(gòu)造查詢方式
這篇文章主要介紹了Spring?JPA使用CriteriaBuilder動態(tài)構(gòu)造查詢方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
IDEA創(chuàng)建SpringBoot項目整合mybatis時mysql-connector-java報錯異常的詳細分析
最近工作中發(fā)現(xiàn)了個錯誤,分享給同樣遇到這個問題的朋友,這篇文章主要給大家介紹了關(guān)于IDEA創(chuàng)建SpringBoot項目整合mybatis時mysql-connector-j報錯異常的詳細分析,需要的朋友可以參考下2023-02-02

