SpringBoot整合kaptcha驗(yàn)證碼過程(復(fù)制粘貼即可用)
SpringBoot整合kaptcha驗(yàn)證碼
前面學(xué)習(xí)了幾種樣式的驗(yàn)證碼驗(yàn)證,Java實(shí)現(xiàn)kaptcha網(wǎng)頁驗(yàn)證碼驗(yàn)證,你會嗎???
作為一個目前以Java后端的為方向的小白,當(dāng)然要寫一個關(guān)于SpringBoot整合kaptcha來實(shí)現(xiàn)驗(yàn)證碼的操作啦,而且以后要用到該功能的話直接復(fù)制粘貼就可以啦~
程序目錄參考

1、首先用idea新建一個spring Initializr
2、添加依賴:
- pom.xml:
<!-- kaptcha驗(yàn)證碼 -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>有兩種方式在springboot中使用kaptcha
- 第一種使用.xml的配置方式配置生成kaptcha的bean對象,在啟動類上@ImportResource這個xml文件;在controller中注入其對象并使用
- 第二種是把kaptcha作為工程的一個類,加上@component注解在返回kaptcha的方法中加上@Bean注解,再在controller中注入其對象。
第一種方式
- mykaptcha.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!-- Kaptcha組件配置 -->
<bean id="kaptchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
<property name="config">
<bean class="com.google.code.kaptcha.util.Config">
<constructor-arg>
<props>
<!-- 驗(yàn)證碼寬度 -->
<prop key="kaptcha.image.width">120</prop>
<!-- 驗(yàn)證碼高度 -->
<prop key="kaptcha.image.height">50</prop>
<!-- 生成驗(yàn)證碼內(nèi)容范圍 -->
<prop key="kaptcha.textproducer.char.string">0123456789AKWUEHPMRX</prop>
<!-- 驗(yàn)證碼個數(shù) -->
<prop key="kaptcha.textproducer.char.length">4</prop>
<!-- 是否有邊框 -->
<prop key="kaptcha.border">no</prop>
<!-- 邊框顏色 -->
<prop key="kaptcha.border.color">105,179,90</prop>
<!-- 邊框厚度 -->
<prop key="kaptcha.border.thickness">1</prop>
<!-- 驗(yàn)證碼字體顏色 -->
<prop key="kaptcha.textproducer.font.color">yellow</prop>
<!-- 驗(yàn)證碼字體大小 -->
<prop key="kaptcha.textproducer.font.size">30</prop>
<!-- 驗(yàn)證碼所屬字體樣式 -->
<prop key="kaptcha.textproducer.font.names">楷體</prop>
<!-- 干擾線顏色 -->
<prop key="kaptcha.noise.color">black</prop>
<!-- 驗(yàn)證碼文本字符間距 -->
<prop key="kaptcha.textproducer.char.space">8</prop>
<!-- 圖片樣式 :陰影-->
<prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.ShadowGimpy</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>
</beans>在springboot啟動類上加上@ImportResource(locations = {“classpath:mykaptcha.xml”}),加了這個注解,springboot就會去加載kaptcha.xml文件
- springboot啟動類:
@SpringBootApplication
@ImportResource(locations = {"classpath:mykaptcha.xml"})
public class SpringbootKaptchaApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootKaptchaApplication.class, args);
}
}第二種方式
寫一個Kaptcha配置類KaptchaConfig。
- KaptchaConfig.java:
@Component
public class KaptchaConfig {
@Bean
public DefaultKaptcha getDefaultKaptcha(){
com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.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", "110");
properties.setProperty("kaptcha.image.height", "40");
properties.setProperty("kaptcha.textproducer.font.size", "30");
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;
}
}這個類用來配置Kaptcha,就相當(dāng)于方法一的mykaptcha.xml,把mykaptcha加入IOC容器,然后return 回一個設(shè)置好屬性的實(shí)例,最后注入到KaptchaController中,在KaptchaController中就可以使用它生成驗(yàn)證碼。
上面的兩種方法選擇其一即可,下面我用XML的方式進(jìn)行操作。
編寫controller用于生成驗(yàn)證碼
- KaptchaController.java:
@Controller
public class KaptchaController {
//第二種方法
//@Qualifier("getDefaultKaptcha")
@Autowired
private Producer captchaProducer = null;
@RequestMapping("/mykaptcha")
public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
response.setContentType("image/jpeg");
//生成驗(yàn)證碼
String capText = captchaProducer.createText();
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
//向客戶端寫出
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
}
}- HelloKaptcha.java:
@RestController
public class HelloKaptcha {
@RequestMapping("/hello")
public String hello(HttpServletRequest request) {
if (!CodeUtil.checkVerifyCode(request)) {
return "驗(yàn)證碼有誤?。?!";
} else {
return "歡迎使用?。?!";
}
}
}編寫工具類util
- CodeUtil.java:
public class CodeUtil {
/**
* 將獲取到的前端參數(shù)轉(zhuǎn)為string類型
*/
public static String getString(HttpServletRequest request, String key) {
try {
String result = request.getParameter(key);
if(result != null) {
result = result.trim();
}
if("".equals(result)) {
result = null;
}
return result;
}catch(Exception e) {
return null;
}
}
/**
* 驗(yàn)證碼校驗(yàn)
*/
public static boolean checkVerifyCode(HttpServletRequest request) {
//獲取生成的驗(yàn)證碼
String verifyCodeExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
//獲取用戶輸入的驗(yàn)證碼
String verifyCodeActual = CodeUtil.getString(request, "verifyCodeActual");
if(verifyCodeActual == null ||!verifyCodeActual.equals(verifyCodeExpected)) {
return false;
}
return true;
}
}這個類用來比對生成的驗(yàn)證碼與用戶輸入的驗(yàn)證碼。生成的驗(yàn)證碼會自動加到session中,用戶輸入的通過getParameter獲得。
- 前端頁面:index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
function refresh() {
document.getElementById('captcha_img').src="/mykaptcha?"+Math.random();
}
</script>
</head>
<body>
<form action="/hello" method="post">
驗(yàn)證碼: <input type="text" placeholder="請輸入驗(yàn)證碼" name="verifyCodeActual">
<div class="item-input">
<img id="captcha_img" alt="點(diǎn)擊更換" title="點(diǎn)擊更換"
onclick="refresh()" src="/mykaptcha" />
</div>
<input type="submit" value="提交" />
</form>
</body>
</html>驗(yàn)證碼本質(zhì)是一張圖片,所以用標(biāo)簽,然后通過src = "/kaptcha"指向生成驗(yàn)證碼的那個controller的路由即可;通過onclick = “refresh()”調(diào)用js代碼實(shí)現(xiàn)點(diǎn)擊切換功能;中要注意name的值,在CodeUtil中通過request的getParameter()方法獲取用戶輸入的驗(yàn)證碼時傳入的key值就應(yīng)該和這里的name值一致。
效果為:


總結(jié):
在用springboot整合kaptcha時操作并不順利,因?yàn)橐婚_始我并不是把所有的程序?qū)懙絾宇惖耐粋€包下,而是寫到了和同級的包下,如:

發(fā)現(xiàn)了嗎???

是的,我居然把使用的程序,沒有寫在啟動類的包下,就這個低級的錯誤讓我卡了一下午,害,說多了都是淚;因?yàn)闆]有寫在啟動類的包下,springboot識別不到,就會出現(xiàn)運(yùn)行時網(wǎng)頁的驗(yàn)證碼無法顯示的情況,如下:

最后在師兄的幫助下才解決了,感謝師兄~
最后附個表以便查閱自己想更改的驗(yàn)證碼圖形:


總結(jié)
關(guān)于SpringBoot整合kaptcha驗(yàn)證碼的使用就到這里。
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot+Druid開啟監(jiān)控頁面的實(shí)現(xiàn)示例
本文主要介紹了SpringBoot+Druid開啟監(jiān)控頁面的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-06-06
springboot mybatis調(diào)用多個數(shù)據(jù)源引發(fā)的錯誤問題
這篇文章主要介紹了springboot mybatis調(diào)用多個數(shù)據(jù)源引發(fā)的錯誤問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
SpringMVC通過注解獲得參數(shù)的實(shí)例
下面小編就為大家?guī)硪黄猄pringMVC通過注解獲得參數(shù)的實(shí)例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08
springboot結(jié)合JWT實(shí)現(xiàn)單點(diǎn)登錄的示例
本文主要介紹了springboot結(jié)合JWT實(shí)現(xiàn)單點(diǎn)登錄的示例,包括生成Token、驗(yàn)證Token及使用Redis存儲Token,具有一定的參考價(jià)值,感興趣的可以了解一下2025-01-01
使用springboot整合mybatis-plus實(shí)現(xiàn)數(shù)據(jù)庫的增刪查改示例
這篇文章主要介紹了使用springboot整合mybatis-plus實(shí)現(xiàn)數(shù)據(jù)庫的增刪查改示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04

