SpringBoot整合Kaptcha實現(xiàn)圖片驗證碼加減乘除功能
SpringBoot整合Kaptcha實現(xiàn)圖片驗證碼加減乘除
在開發(fā)Web應(yīng)用時,驗證碼是一個常見的功能,它可以幫助我們防止機(jī)器人的惡意操作。今天我們將學(xué)習(xí)如何使用Kaptcha生成圖片驗證碼,并自定義驗證碼內(nèi)容為100以內(nèi)的加減乘除運算。
1. 添加Kaptcha依賴
首先,確保你的項目中包含Kaptcha的依賴。對于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>
2. 自定義文本生成器
我們需要創(chuàng)建一個自定義的文本生成器MathKaptchaTextCreator
,它將生成包含加減乘除運算的驗證碼內(nèi)容。
package com.bangbang.tracesource.admin.conf; import com.google.code.kaptcha.text.impl.DefaultTextCreator; import java.util.Random; public class MathKaptchaTextCreator extends DefaultTextCreator { @Override public String getText() { Random random = new Random(); int x = random.nextInt(100); int y = random.nextInt(100); String[] operators = {"+", "-", "*", "/"}; String operator = operators[random.nextInt(4)]; String expression = x + operator + y; int result = 0; switch (operator) { case "+": result = x + y; break; case "-": result = x - y; break; case "*": result = x * y; break; case "/": result = y == 0 ? x : x / y; break; } return expression + "=?@" + result; } }
在這個實現(xiàn)中,我們生成了一個隨機(jī)的加減乘除運算表達(dá)式,并將其結(jié)果附加在表達(dá)式的末尾,以@
分隔。例如:1+1=?@2
。
3. 配置Kaptcha
接下來,創(chuàng)建一個配置類KaptchaConfig
來配置Kaptcha的屬性,并指定我們的自定義文本生成器。
import com.google.code.kaptcha.impl.DefaultKaptcha; import com.google.code.kaptcha.util.Config; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import java.util.Properties; @Component public class KaptchaConfig { @Bean public DefaultKaptcha getDefaultKaptcha() { 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", "black"); properties.setProperty("kaptcha.image.width", "110"); properties.setProperty("kaptcha.image.height", "40"); properties.setProperty("kaptcha.textproducer.font.size", "35"); properties.setProperty("kaptcha.session.key", "code"); properties.setProperty("kaptcha.textproducer.impl", "com.shy.admin.conf.MathKaptchaTextCreator"); properties.setProperty("kaptcha.textproducer.font.names", "宋體,楷體,微軟雅黑"); // 設(shè)置干擾線 properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.FishEyeGimpy"); Config config = new Config(properties); defaultKaptcha.setConfig(config); return defaultKaptcha; } }
4. 獲取驗證碼圖片的方法
我們還需要一個控制器方法來生成和返回驗證碼圖片。
import com.google.code.kaptcha.impl.DefaultKaptcha; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; public class KaptchaController { @Autowired private DefaultKaptcha defaultKaptcha; @RequestMapping(value = "/kaptcha", method = RequestMethod.GET) public void getKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException { byte[] captchaChallengeAsJpeg; ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); try { // 生產(chǎn)驗證碼字符串并保存到session中 eg: 3-2=?@1 String createText = defaultKaptcha.createText(); // capStr就是算術(shù)題 也就是用戶看到的驗證碼 String capStr = createText.substring(0, createText.lastIndexOf("@")); // code 就是算術(shù)的結(jié)果 也就是輸入的驗證碼 String code = createText.substring(createText.lastIndexOf("@") + 1); httpServletRequest.getSession().setAttribute("KAPTCHA_SESSION_KEY", code); // 使用生產(chǎn)的驗證碼字符串返回一個BufferedImage對象并轉(zhuǎn)為byte寫入到byte數(shù)組中 BufferedImage challenge = defaultKaptcha.createImage(capStr); ImageIO.write(challenge, "jpg", jpegOutputStream); } catch (IllegalArgumentException e) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); httpServletResponse.setHeader("Cache-Control", "no-store"); httpServletResponse.setHeader("Pragma", "no-cache"); httpServletResponse.setDateHeader("Expires", 0); httpServletResponse.setContentType("image/jpeg"); httpServletResponse.getOutputStream().write(captchaChallengeAsJpeg); httpServletResponse.getOutputStream().flush(); } }
4.1. 詳細(xì)講解控制器中的切割操作
在控制器方法中,我們生成了驗證碼文本并將其保存在session中。生成的驗證碼文本格式為:1+1=?@2
。接下來,我們需要將表達(dá)式和結(jié)果分離開來,以便將結(jié)果保存在session中用于驗證用戶輸入。
// 生產(chǎn)驗證碼字符串并保存到session中 eg: 3-2=?@1 String createText = defaultKaptcha.createText(); // capStr就是算術(shù)題 也就是用戶看到的驗證碼 String capStr = createText.substring(0, createText.lastIndexOf("@")); // code 就是算術(shù)的結(jié)果 也就是輸入的驗證碼 String code = createText.substring(createText.lastIndexOf("@") + 1); httpServletRequest.getSession().setAttribute("KAPTCHA_SESSION_KEY", code);
在這段代碼中:
createText = defaultKaptcha.createText();
:生成驗證碼文本,例如:1+1=?@2
。capStr = createText.substring(0, createText.lastIndexOf("@"));
:獲取運算表達(dá)式部分,即1+1=?
。code = createText.substring(createText.lastIndexOf("@") + 1);
:獲取運算結(jié)果部分,即2
。httpServletRequest.getSession().setAttribute("KAPTCHA_SESSION_KEY", code);
:將運算結(jié)果保存到session中,用于后續(xù)的驗證。
通過這種方式,我們可以將驗證碼的運算表達(dá)式和結(jié)果分離開來,用戶看到的是表達(dá)式部分,而驗證時使用的是結(jié)果部分。
生成的驗證碼如下圖所示:
5. 總結(jié)
通過上述步驟,我們實現(xiàn)了一個自定義的Kaptcha圖片驗證碼生成器,該生成器可以生成包含100以內(nèi)的加減乘除運算的驗證碼。通過這種方式,我們不僅可以提高驗證碼的安全性,還能增強用戶體驗。
到此這篇關(guān)于SpringBoot整合Kaptcha實現(xiàn)圖片驗證碼加減乘除的文章就介紹到這了,更多相關(guān)SpringBoot Kaptcha圖片驗證碼加減乘除內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java使用阻塞隊列BlockingQueue實現(xiàn)生產(chǎn)者消費者的方法
BlockingQueue是一個支持阻塞插入和移除操作的隊列,常用于多線程環(huán)境下的生產(chǎn)者和消費者場景,文章介紹了阻塞隊列BlockingQueue的概念和其在生產(chǎn)者消費者模式中的應(yīng)用,提供了一個簡單的示例,展示了如何使用ArrayBlockingQueue來實現(xiàn)生產(chǎn)者消費者模式2024-11-11解析web.xml中在Servlet中獲取context-param和init-param內(nèi)的參數(shù)
本篇文章是對web.xml中在Servlet中獲取context-param和init-param內(nèi)的參數(shù)進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-07-07Java版C語言版簡單使用靜態(tài)語言實現(xiàn)動態(tài)數(shù)組的方法
本文給大家分享java版和C語言版簡單使用靜態(tài)語言實現(xiàn)動態(tài)數(shù)組的方法,非常不錯,具有參考借鑒價值,需要的朋友參考下吧2017-10-10