SpringBoot整合kaptcha驗(yàn)證碼過程(復(fù)制粘貼即可用)
SpringBoot整合kaptcha驗(yàn)證碼
前面學(xué)習(xí)了幾種樣式的驗(yàn)證碼驗(yàn)證,Java實(shí)現(xiàn)kaptcha網(wǎng)頁(yè)驗(yàn)證碼驗(yàn)證,你會(huì)嗎???
作為一個(gè)目前以Java后端的為方向的小白,當(dāng)然要寫一個(gè)關(guān)于SpringBoot整合kaptcha來(lái)實(shí)現(xiàn)驗(yàn)證碼的操作啦,而且以后要用到該功能的話直接復(fù)制粘貼就可以啦~
程序目錄參考
1、首先用idea新建一個(gè)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對(duì)象,在啟動(dòng)類上@ImportResource這個(gè)xml文件;在controller中注入其對(duì)象并使用
- 第二種是把kaptcha作為工程的一個(gè)類,加上@component注解在返回kaptcha的方法中加上@Bean注解,再在controller中注入其對(duì)象。
第一種方式
- 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)證碼個(gè)數(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啟動(dòng)類上加上@ImportResource(locations = {“classpath:mykaptcha.xml”}),加了這個(gè)注解,springboot就會(huì)去加載kaptcha.xml文件
- springboot啟動(dòng)類:
@SpringBootApplication @ImportResource(locations = {"classpath:mykaptcha.xml"}) public class SpringbootKaptchaApplication { public static void main(String[] args) { SpringApplication.run(SpringbootKaptchaApplication.class, args); } }
第二種方式
寫一個(gè)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; } }
這個(gè)類用來(lái)配置Kaptcha,就相當(dāng)于方法一的mykaptcha.xml,把mykaptcha加入IOC容器,然后return 回一個(gè)設(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; } }
這個(gè)類用來(lái)比對(duì)生成的驗(yàn)證碼與用戶輸入的驗(yàn)證碼。生成的驗(yàn)證碼會(huì)自動(dòng)加到session中,用戶輸入的通過getParameter獲得。
- 前端頁(yè)面: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="請(qǐng)輸入驗(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)證碼的那個(gè)controller的路由即可;通過onclick = “refresh()”調(diào)用js代碼實(shí)現(xiàn)點(diǎn)擊切換功能;中要注意name的值,在CodeUtil中通過request的getParameter()方法獲取用戶輸入的驗(yàn)證碼時(shí)傳入的key值就應(yīng)該和這里的name值一致。
效果為:
總結(jié):
在用springboot整合kaptcha時(shí)操作并不順利,因?yàn)橐婚_始我并不是把所有的程序?qū)懙絾?dòng)類的同一個(gè)包下,而是寫到了和同級(jí)的包下,如:
發(fā)現(xiàn)了嗎???
是的,我居然把使用的程序,沒有寫在啟動(dòng)類的包下,就這個(gè)低級(jí)的錯(cuò)誤讓我卡了一下午,害,說(shuō)多了都是淚;因?yàn)闆]有寫在啟動(dòng)類的包下,springboot識(shí)別不到,就會(huì)出現(xiàn)運(yùn)行時(shí)網(wǎng)頁(yè)的驗(yàn)證碼無(wú)法顯示的情況,如下:
最后在師兄的幫助下才解決了,感謝師兄~
最后附個(gè)表以便查閱自己想更改的驗(yàn)證碼圖形:
總結(jié)
關(guān)于SpringBoot整合kaptcha驗(yàn)證碼的使用就到這里。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot+Druid開啟監(jiān)控頁(yè)面的實(shí)現(xiàn)示例
本文主要介紹了SpringBoot+Druid開啟監(jiān)控頁(yè)面的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-06-06springboot mybatis調(diào)用多個(gè)數(shù)據(jù)源引發(fā)的錯(cuò)誤問題
這篇文章主要介紹了springboot mybatis調(diào)用多個(gè)數(shù)據(jù)源引發(fā)的錯(cuò)誤問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01SpringMVC通過注解獲得參數(shù)的實(shí)例
下面小編就為大家?guī)?lái)一篇SpringMVC通過注解獲得參數(shù)的實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2017-08-08springboot結(jié)合JWT實(shí)現(xiàn)單點(diǎn)登錄的示例
本文主要介紹了springboot結(jié)合JWT實(shí)現(xiàn)單點(diǎn)登錄的示例,包括生成Token、驗(yàn)證Token及使用Redis存儲(chǔ)Token,具有一定的參考價(jià)值,感興趣的可以了解一下2025-01-01使用springboot整合mybatis-plus實(shí)現(xiàn)數(shù)據(jù)庫(kù)的增刪查改示例
這篇文章主要介紹了使用springboot整合mybatis-plus實(shí)現(xiàn)數(shù)據(jù)庫(kù)的增刪查改示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04帶你重新認(rèn)識(shí)Java動(dòng)態(tài)代理
這篇文章主要為大家介紹了Java的動(dòng)態(tài)代理,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2021-11-11