SpringBoot整合Kaptcha實現(xiàn)圖片驗證碼加減乘除功能
SpringBoot整合Kaptcha實現(xiàn)圖片驗證碼加減乘除
在開發(fā)Web應用時,驗證碼是一個常見的功能,它可以幫助我們防止機器人的惡意操作。今天我們將學習如何使用Kaptcha生成圖片驗證碼,并自定義驗證碼內容為100以內的加減乘除運算。
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,它將生成包含加減乘除運算的驗證碼內容。
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)中,我們生成了一個隨機的加減乘除運算表達式,并將其結果附加在表達式的末尾,以@分隔。例如: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", "宋體,楷體,微軟雅黑");
// 設置干擾線
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 {
// 生產驗證碼字符串并保存到session中 eg: 3-2=?@1
String createText = defaultKaptcha.createText();
// capStr就是算術題 也就是用戶看到的驗證碼
String capStr = createText.substring(0, createText.lastIndexOf("@"));
// code 就是算術的結果 也就是輸入的驗證碼
String code = createText.substring(createText.lastIndexOf("@") + 1);
httpServletRequest.getSession().setAttribute("KAPTCHA_SESSION_KEY", code);
// 使用生產的驗證碼字符串返回一個BufferedImage對象并轉為byte寫入到byte數組中
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. 詳細講解控制器中的切割操作
在控制器方法中,我們生成了驗證碼文本并將其保存在session中。生成的驗證碼文本格式為:1+1=?@2。接下來,我們需要將表達式和結果分離開來,以便將結果保存在session中用于驗證用戶輸入。
// 生產驗證碼字符串并保存到session中 eg: 3-2=?@1
String createText = defaultKaptcha.createText();
// capStr就是算術題 也就是用戶看到的驗證碼
String capStr = createText.substring(0, createText.lastIndexOf("@"));
// code 就是算術的結果 也就是輸入的驗證碼
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("@"));:獲取運算表達式部分,即1+1=?。code = createText.substring(createText.lastIndexOf("@") + 1);:獲取運算結果部分,即2。httpServletRequest.getSession().setAttribute("KAPTCHA_SESSION_KEY", code);:將運算結果保存到session中,用于后續(xù)的驗證。
通過這種方式,我們可以將驗證碼的運算表達式和結果分離開來,用戶看到的是表達式部分,而驗證時使用的是結果部分。
生成的驗證碼如下圖所示:

5. 總結
通過上述步驟,我們實現(xiàn)了一個自定義的Kaptcha圖片驗證碼生成器,該生成器可以生成包含100以內的加減乘除運算的驗證碼。通過這種方式,我們不僅可以提高驗證碼的安全性,還能增強用戶體驗。
到此這篇關于SpringBoot整合Kaptcha實現(xiàn)圖片驗證碼加減乘除的文章就介紹到這了,更多相關SpringBoot Kaptcha圖片驗證碼加減乘除內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java使用阻塞隊列BlockingQueue實現(xiàn)生產者消費者的方法
BlockingQueue是一個支持阻塞插入和移除操作的隊列,常用于多線程環(huán)境下的生產者和消費者場景,文章介紹了阻塞隊列BlockingQueue的概念和其在生產者消費者模式中的應用,提供了一個簡單的示例,展示了如何使用ArrayBlockingQueue來實現(xiàn)生產者消費者模式2024-11-11
解析web.xml中在Servlet中獲取context-param和init-param內的參數
本篇文章是對web.xml中在Servlet中獲取context-param和init-param內的參數進行了詳細的分析介紹,需要的朋友參考下2013-07-07
Java版C語言版簡單使用靜態(tài)語言實現(xiàn)動態(tài)數組的方法
本文給大家分享java版和C語言版簡單使用靜態(tài)語言實現(xiàn)動態(tài)數組的方法,非常不錯,具有參考借鑒價值,需要的朋友參考下吧2017-10-10

