Google Kaptcha 框架實現(xiàn)登錄驗證碼功能(SSM 和 SpringBoot)
一、效果圖:

二、導(dǎo)入 jar 包
1.由于這是大神寫好封裝起來的一個框架,所有我們使用前得先下載相關(guān)的 jar 包
第一種:maven
<!-- 驗證碼 --> <!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha --> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
第二種:lib
打開鏈接:https://mvnrepository.com/artifact/com.github.penggle/kaptcha


三、SSM 通過 Kaptcha 簡單實現(xiàn)驗證碼
直接在 web.xml 里面直接配置
驗證碼的一些樣式都是通過配置來實現(xiàn)的,下面是我自己使用的一個demo,如果需要更改字體顏色還有字體大小什么的等,可以自己根據(jù)注釋來修改。不然直接復(fù)制粘貼也行。由于配置比較簡單,不作過多解釋,直接上代碼。
<!-- 驗證碼相關(guān)屬性的配置 --> <servlet> <servlet-name>Kaptcha</servlet-name> <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> <!-- 定義 Kaptcha 的樣式 --> <!-- 是否有邊框 --> <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>135</param-value> </init-param> <!-- 圖片高度 --> <init-param> <param-name>kaptcha.image.height</param-name> <param-value>50</param-value> </init-param> <!-- 使用哪些字符生成驗證碼 --> <init-param> <param-name>kaptcha.textproducer.char.string</param-name> <param-value>ACDEFHKPRSTWX345975</param-value> </init-param> <!-- 字體大小 --> <init-param> <param-name>kaptcha.textproducer.font.size</param-name> <param-value>43</param-value> </init-param> <!-- 干擾線的顏色 --> <init-param> <param-name>kaptcha.noise.color</param-name> <param-value>black</param-value> </init-param> <!-- 字符個數(shù) --> <init-param> <param-name>kaptcha.textproducer.char.length</param-name> <param-value>4</param-value> </init-param> <!-- 字體 --> <init-param> <param-name>kaptcha.textproducer.font.names</param-name> <param-value>Arial</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Kaptcha</servlet-name> <!-- 外部訪問路徑 --> <url-pattern>/Kaptcha</url-pattern> </servlet-mapping>
3.前端驗證碼的顯示實現(xiàn)
div class="item-inner">
<div class="item-title label">驗證碼</div>
<input type="text" id="j_captcha" placeholder="驗證碼">
<div class="item-input">
<img id="captcha_img" alt="點擊更換" title="點擊更換"
onclick="changeVerifyCode(this)" src="../Kaptcha"/>
</div>
</div>
function changeVerifyCode(img){
img.src="../Kaptcha?" + Math.floor(Math.random()*100);
}
解釋:
驗證碼圖片的鏈接 src 中的 "../Kaptcha",這里的“Kaptcha”是要與剛剛 web.xml 中的 url-pattern 配置的值一樣的,并非隨便寫的。
4.后端進(jìn)行驗證碼的輸入驗證
實現(xiàn)思路:我是把驗證碼的驗證單獨寫成一個靜態(tài)類,然后在控制層里面直接調(diào)用就行。
驗證碼靜態(tài)類:
public class CodeUtil {
public static boolean checkVerifyCode(HttpServletRequest request){
String verifyCodeExpected = (String)request.getSession().getAttribute(
com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
//這里相當(dāng)于 request.getParameter("verifyCodeActual");
String verifyCodeActual = HttpServletRequestUtil.getString(request, "verifyCodeActual");
if(verifyCodeActual == null || verifyCodeActual.equals(verifyCodeExpected)){
return false;
}
return true;
}}
控制層調(diào)用代碼:
if(!CodeUtil.checkVerifyCode(request)){
modelMap.put("success", false);
modelMap.put("errMsg", "輸入了錯誤的驗證碼");
return modelMap;
}
modelMap.put("success", false);
modelMap.put("errMsg", "輸入了錯誤的驗證碼");
return modelMap;
}
if 里面驗證碼不通過(錯誤)的時候,我自己做的一些處理,可以根據(jù)自己的實際情況進(jìn)行修改。
SSM 環(huán)境下 Kaptcha 的使用就介紹完了。
四、SpringBoot 通過 Kaptcha 簡單實現(xiàn)驗證碼
思路:將 xml 的形勢轉(zhuǎn)化成代碼實現(xiàn)。
package com.example.demo.config;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class KaptchaController {
@Bean(name="captchaProducer")
public DefaultKaptcha getKaptchaBean(){
DefaultKaptcha defaultKaptcha=new DefaultKaptcha();
Properties properties=new Properties();
properties.setProperty("kaptcha.border", "yes");
properties.setProperty("kaptcha.border.color", "105,179,90");
properties.setProperty("kaptcha.textproducer.font.color", "blue");
properties.setProperty("kaptcha.image.width", "125");
properties.setProperty("kaptcha.image.height", "45");
properties.setProperty("kaptcha.session.key", "code");
properties.setProperty("kaptcha.textproducer.char.length", "4");
properties.setProperty("kaptcha.textproducer.font.names", "宋體,楷體,微軟雅黑");
Config config=new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
編寫一個 controller 類。
package com.example.demo.controller;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
@Controller
public class ChaController {
@Autowired
private Producer captchaProducer;
@GetMapping("/getKaptchaImage")
public void getKaptchaImage(HttpServletResponse response,HttpSession session) throws Exception {
response.setDateHeader("Expires", 0);
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
// return a jpeg
response.setContentType("image/jpeg");
// create the text for the image
String capText = captchaProducer.createText();
// store the text in the session
//request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
//將驗證碼存到session
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
// create the image with the text
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
// write the data out
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
}
}
前端代碼:
<img id="captcha_img" alt="點擊更換" title="點擊更換"
onclick="changeVerifyCode(this)" src="../getKaptchaImage"/>
至于點擊切換驗證碼還有后臺如何接受驗證,跟前面 SSM 的使用方法一樣,這里就不再贅述。
我們可以直接啟動 springboot 的項目,在瀏覽器上直接訪問獲取驗證碼的接口。
http://localhost:8080/getKaptchaImage
就能在瀏覽器上看到驗證碼的圖片了,說明配置是成功的。

五、Kaptcha 屬性表




總結(jié)
以上所述是小編給大家介紹的Google Kaptcha 框架實現(xiàn)登錄驗證碼功能(SSM 和 SpringBoot),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
這么設(shè)置IDEA中的Maven,再也不用擔(dān)心依賴下載失敗了
今天給大家?guī)硪粋€IDEA中Maven設(shè)置的小技巧.這個技巧可以說非常有用,學(xué)會設(shè)置之后,再也不用擔(dān)心maven依賴下載變慢的問題,需要的朋友可以參考下2021-05-05
Springboot3利用redis生成唯一訂單號的實現(xiàn)示例
本文主要介紹了Springboot3利用redis生成唯一訂單號的實現(xiàn)示例,包括UUID、雪花算法和數(shù)據(jù)庫約束,具有一定的參考價值,感興趣的可以了解一下2025-03-03
Java Web使用Html5 FormData實現(xiàn)多文件上傳功能
這篇文章主要介紹了Java Web使用Html5 FormData實現(xiàn)多文件上傳功能,需要的朋友可以參考下2017-07-07
SpringMVC中的HttpServletRequestWrapper使用解析
這篇文章主要介紹了SpringMVC中的HttpServletRequestWrapper使用解析,HttpServletRequestWrapper 采用裝飾者模式對HttpServletRequest進(jìn)行包裝,我們可以通過繼承HttpServletRequestWrapper類去重寫getParameterValues,getParameter等方法,需要的朋友可以參考下2024-01-01
Servlet+JDBC實現(xiàn)登陸功能的小例子(帶驗證碼)
這篇文章主要介紹了Servlet+JDBC實現(xiàn)登陸功能的小例子(帶驗證碼),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
SpringBoot接口正確接收時間參數(shù)的幾種方式
這篇文章主要給大家介紹了關(guān)于SpringBoot接口正確接收時間參數(shù)的相關(guān)資料,文中通過代碼示例介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用springboot具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09
spring-data-jpa中findOne與getOne的區(qū)別說明
這篇文章主要介紹了spring-data-jpa中findOne與getOne的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
spring cloud gateway使用 uri: lb://方式配置時,服務(wù)名的特殊要求
這篇文章主要介紹了spring cloud gateway使用 uri: lb://方式配置時,服務(wù)名的特殊要求,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12

