springboot整合kaptcha驗(yàn)證碼的示例代碼
前言:
關(guān)于kaptcha簡介以及spring整合kaptcha,我在另一篇文章中已詳細(xì)講解,請參考:spring整合kaptcha驗(yàn)證碼。
本文將介紹springboot整合kaptcha的兩種方式。
開發(fā)工具及技術(shù):
1、idea 2017
2、springboot 2.0.2
3、kaptcha
正式開始:
方式一:通過kaptcha.xml配置
1、用idea新建一個(gè)spring Initializr
2、添加kaptcha的依賴:
<!-- kaptcha驗(yàn)證碼 --> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
3、在resources下面新建kaptcha.xml,內(nèi)容如下:
kaptcha.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.xsd"> <!-- 生成kaptcha的bean--> <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha"> <property name="config"> <bean class="com.google.code.kaptcha.util.Config"> <constructor-arg type="java.util.Properties"> <!--設(shè)置kaptcha屬性 --> <props> <prop key = "kaptcha.border ">yes</prop> <prop key="kaptcha.border.color">105,179,90</prop> <prop key="kaptcha.textproducer.font.color">blue</prop> <prop key="kaptcha.image.width">100</prop> <prop key="kaptcha.image.height">50</prop> <prop key="kaptcha.textproducer.font.size">27</prop> <prop key="kaptcha.session.key">code</prop> <prop key="kaptcha.textproducer.char.length">4</prop> <prop key="kaptcha.textproducer.font.names">宋體,楷體,微軟雅黑</prop> <prop key="kaptcha.textproducer.char.string">0123456789ABCEFGHIJKLMNOPQRSTUVWXYZ</prop> <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.WaterRipple</prop> <prop key="kaptcha.noise.color">black</prop> <prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.DefaultNoise</prop> <prop key="kaptcha.background.clear.from">185,56,213</prop> <prop key="kaptcha.background.clear.to">white</prop> <prop key="kaptcha.textproducer.char.space">3</prop> </props> </constructor-arg> </bean> </property> </bean> </beans>
注:kaptcha.xml中的內(nèi)容其實(shí)就是和spring 整合kaptcha時(shí)spring-kaptcha.xml中內(nèi)容一樣,就是將kaptcha交給spring容器管理,設(shè)置一些屬性,然后要用的時(shí)候直接注入即可。
4、加載kaptcha.xml:
在springboot啟動(dòng)類上加上@ImportResource(locations = {"classpath:kaptcha/kaptcha.xml"}),
加了這個(gè)注解,springboot就會(huì)去加載kaptcha.xml文件。注意kaptcha.xml的路徑不要寫錯(cuò),classpath在此處是resources目錄。
5、編寫controller用于生成驗(yàn)證碼:
CodeController.java
@Controller public class CodeController { @Autowired private Producer captchaProducer = null; @RequestMapping("/kaptcha") 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(); } } }
注:在這個(gè)controller徑注入剛剛kaptcha.xml中配置的那個(gè)bean,然后就可以使用它生成驗(yàn)證碼,以及向客戶端輸出驗(yàn)證碼;記住這個(gè)類的路由,前端頁面驗(yàn)證碼的src需要指向這個(gè)路由。
6、新建驗(yàn)證碼比對工具類:
CodeUtil.java
public class CodeUtil { /** * 將獲取到的前端參數(shù)轉(zhuǎn)為string類型 * @param request * @param key * @return */ 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) * @param request * @return */ 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è)類用來比對生成的驗(yàn)證碼與用戶輸入的驗(yàn)證碼。生成的驗(yàn)證碼會(huì)自動(dòng)加到session中,用戶輸入的通過getParameter獲得。注意getParameter的key值要與頁面中驗(yàn)證碼的name值一致。
7、使用驗(yàn)證碼:
①Controller
HelloWorld.java
@RestController public class HelloWorld { @RequestMapping("/hello") public String hello(HttpServletRequest request) { if (!CodeUtil.checkVerifyCode(request)) { return "驗(yàn)證碼有誤!"; } else { return "hello,world"; } } }
②頁面
hello.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="/kaptcha?"+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="/kaptcha" /> </div> <input type="submit" value="提交" /> </form> </body> </html>
注意:驗(yàn)證碼本質(zhì)是一張圖片,所以用<img >標(biāo)簽,然后通過src = "/kaptcha"指向生成驗(yàn)證碼的那個(gè)controller的路由即可;通過onclick = “refresh()”調(diào)用js代碼實(shí)現(xiàn)點(diǎn)擊切換功能;<input name = "verifyCodeActual ">中要注意name的值,在CodeUtil中通過request的getParameter()方法獲取用戶輸入的驗(yàn)證碼時(shí)傳入的key值就應(yīng)該和這里的name值一致。
8、測試:
輸入正確的驗(yàn)證碼
驗(yàn)證通過
輸入錯(cuò)誤的驗(yàn)證碼
驗(yàn)證未通過
方式二:通過配置類來配置kaptcha
1、配置kaptcha
相比于方式一,一增二減。
減:
①把kaptcha.xml刪掉
②把啟動(dòng)類上的@ImportResource(locations = {"classpath:kaptcha/kaptcha.xml"})
注解刪掉
增:
①新建KaptchaConfig配置類,內(nèi)容如下:
KaptchaConfig.java
@Configuration public class KaptchaConfig { @Bean public DefaultKaptcha getDefaultKaptcha(){ DefaultKaptcha captchaProducer = 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", "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); captchaProducer.setConfig(config); return captchaProducer; } }
注:這個(gè)類用來配置Kaptcha,就相當(dāng)于方式一的kaptcha.xml,把kaptcha加入IOC容器,然后return 回一個(gè)設(shè)置好屬性的實(shí)例,最后注入到CodeController中,在CodeController中就可以使用它生成驗(yàn)證碼。要特別注意return captchaProducer;與private Producer captchaProducer = null;中captchaProducer名字要一樣,不然就加載不到這個(gè)bean。
2、測試:
輸入正確的驗(yàn)證碼:
驗(yàn)證通過
輸入錯(cuò)誤的驗(yàn)證碼
驗(yàn)證未通過
為了說明兩次的驗(yàn)證碼是基于兩種方式生成的,方式一和方式二的驗(yàn)證碼我設(shè)置了不同的屬性,從圖片中可以看出兩次驗(yàn)證碼的顏色、干擾線、背景等都有不同。
總結(jié):
1、過程梳理:
不論是哪種方式,都是先把kaptcha加入spring容器,即要有一個(gè)kaptcha的bean;再新建一個(gè)controller,把kaptcha的bean注入到controller中用于生成驗(yàn)證碼;然后需要有一個(gè)比對驗(yàn)證碼的工具類,在測試的controller中調(diào)用工具類進(jìn)行驗(yàn)證碼比對;最后在前端頁面只需要用一個(gè)<img src = "/生成驗(yàn)證碼的controller的路由">
即可獲取驗(yàn)證碼,通過給這個(gè)img標(biāo)簽加點(diǎn)擊事件就可實(shí)現(xiàn)“點(diǎn)擊切換驗(yàn)證碼”。
2、與spring整合kaptcha對比
spring整合kaptcha也介紹了兩種方式,在web.xml中配置最簡潔,不需要寫生成驗(yàn)證碼的controller,在頁面中直接用src指向web.xml中kaptcha的servlet 的<url-pattern >的值即可。
springboot整合kaptcha的兩種方式都類似于spring整合kaptcha的第二種方式,都是先配置bean,然后用controller生成驗(yàn)證碼,前端用src指向這個(gè)controller,不同之處在于:假如生成驗(yàn)證碼的controller路由為/xxx,那么spring 整合kaptcha時(shí)src = “xxx.jpg”,springboot整合kaptcha時(shí)src = "/xxx"。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- SpringBoot+kaptcha實(shí)現(xiàn)圖片驗(yàn)證碼功能詳解
- SpringBoot整合kaptcha實(shí)現(xiàn)圖片驗(yàn)證碼功能
- Springboot?+redis+谷歌開源Kaptcha實(shí)現(xiàn)圖片驗(yàn)證碼功能
- SpringBoot集成Kaptcha驗(yàn)證碼的詳細(xì)過程
- SpringBoot使用Kaptcha實(shí)現(xiàn)驗(yàn)證碼的生成與驗(yàn)證功能
- SpringBoot+kaptcha實(shí)現(xiàn)驗(yàn)證碼花式玩法詳解
- Google Kaptcha 框架實(shí)現(xiàn)登錄驗(yàn)證碼功能(SSM 和 SpringBoot)
- SpringBoot 集成Kaptcha實(shí)現(xiàn)驗(yàn)證碼功能實(shí)例詳解
- SpringBoot整合Kaptcha實(shí)現(xiàn)圖片驗(yàn)證碼加減乘除功能
相關(guān)文章
MybatisPlus lambdaQueryWrapper中常用方法的使用
本文主要介紹了MybatisPlus lambdaQueryWrapper中常用方法的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07Java日期格式化的實(shí)現(xiàn)(@JsonFormat和@JSONField)
本文主要介紹了Java日期格式化的實(shí)現(xiàn),主要介紹了@JsonFormat和@JSONField兩種方式,具有一定的參考價(jià)值,感興趣的可以了解一下2024-05-05Mybatis?大數(shù)據(jù)量批量寫優(yōu)化的案例詳解
這篇文章主要介紹了Mybatis?大數(shù)據(jù)量批量寫優(yōu)化的示例代碼,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-05-05Spring Boot解決項(xiàng)目啟動(dòng)時(shí)初始化資源的方法
這篇文章主要給大家介紹了關(guān)于Spring Boot如何解決項(xiàng)目啟動(dòng)時(shí)初始化資源的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-05-05mybatis?mapper.xml中如何根據(jù)數(shù)據(jù)庫類型選擇對應(yīng)SQL語句
這篇文章主要介紹了mybatis?mapper.xml中如何根據(jù)數(shù)據(jù)庫類型選擇對應(yīng)SQL語句,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01詳解SpringMVC中設(shè)置靜態(tài)資源不被攔截的問題
這篇文章主要介紹了詳解SpringMVC中設(shè)置靜態(tài)資源不被攔截的問題,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-02-02Java實(shí)現(xiàn)InputStream的任意拷貝方式
這篇文章主要介紹了Java實(shí)現(xiàn)InputStream的任意拷貝方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10Java 實(shí)現(xiàn)LZ78壓縮算法的示例代碼
這篇文章主要介紹了Java 實(shí)現(xiàn)LZ78壓縮算法的示例代碼,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-05-05java 定時(shí)同步數(shù)據(jù)的任務(wù)優(yōu)化
這篇文章主要介紹了java 定時(shí)同步數(shù)據(jù)的任務(wù)優(yōu)化,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-12-12