springboot整合kaptcha驗證碼的示例代碼
前言:
關(guān)于kaptcha簡介以及spring整合kaptcha,我在另一篇文章中已詳細講解,請參考:spring整合kaptcha驗證碼。
本文將介紹springboot整合kaptcha的兩種方式。
開發(fā)工具及技術(shù):
1、idea 2017
2、springboot 2.0.2
3、kaptcha
正式開始:
方式一:通過kaptcha.xml配置
1、用idea新建一個spring Initializr
2、添加kaptcha的依賴:
<!-- kaptcha驗證碼 --> <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)容其實就是和spring 整合kaptcha時spring-kaptcha.xml中內(nèi)容一樣,就是將kaptcha交給spring容器管理,設(shè)置一些屬性,然后要用的時候直接注入即可。
4、加載kaptcha.xml:
在springboot啟動類上加上@ImportResource(locations = {"classpath:kaptcha/kaptcha.xml"}),
加了這個注解,springboot就會去加載kaptcha.xml文件。注意kaptcha.xml的路徑不要寫錯,classpath在此處是resources目錄。
5、編寫controller用于生成驗證碼:
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"); //生成驗證碼 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(); } } }
注:在這個controller徑注入剛剛kaptcha.xml中配置的那個bean,然后就可以使用它生成驗證碼,以及向客戶端輸出驗證碼;記住這個類的路由,前端頁面驗證碼的src需要指向這個路由。
6、新建驗證碼比對工具類:
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; } } /** * 驗證碼校驗 * @param request * @return */ public static boolean checkVerifyCode(HttpServletRequest request) { //獲取生成的驗證碼 String verifyCodeExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); //獲取用戶輸入的驗證碼 String verifyCodeActual = CodeUtil.getString(request, "verifyCodeActual"); if(verifyCodeActual == null ||!verifyCodeActual.equals(verifyCodeExpected)) { return false; } return true; } }
注:這個類用來比對生成的驗證碼與用戶輸入的驗證碼。生成的驗證碼會自動加到session中,用戶輸入的通過getParameter獲得。注意getParameter的key值要與頁面中驗證碼的name值一致。
7、使用驗證碼:
①Controller
HelloWorld.java
@RestController public class HelloWorld { @RequestMapping("/hello") public String hello(HttpServletRequest request) { if (!CodeUtil.checkVerifyCode(request)) { return "驗證碼有誤!"; } 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"> 驗證碼: <input type="text" placeholder="請輸入驗證碼" name="verifyCodeActual"> <div class="item-input"> <img id="captcha_img" alt="點擊更換" title="點擊更換" onclick="refresh()" src="/kaptcha" /> </div> <input type="submit" value="提交" /> </form> </body> </html>
注意:驗證碼本質(zhì)是一張圖片,所以用<img >標簽,然后通過src = "/kaptcha"指向生成驗證碼的那個controller的路由即可;通過onclick = “refresh()”調(diào)用js代碼實現(xiàn)點擊切換功能;<input name = "verifyCodeActual ">中要注意name的值,在CodeUtil中通過request的getParameter()方法獲取用戶輸入的驗證碼時傳入的key值就應該和這里的name值一致。
8、測試:
輸入正確的驗證碼
驗證通過
輸入錯誤的驗證碼
驗證未通過
方式二:通過配置類來配置kaptcha
1、配置kaptcha
相比于方式一,一增二減。
減:
①把kaptcha.xml刪掉
②把啟動類上的@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; } }
注:這個類用來配置Kaptcha,就相當于方式一的kaptcha.xml,把kaptcha加入IOC容器,然后return 回一個設(shè)置好屬性的實例,最后注入到CodeController中,在CodeController中就可以使用它生成驗證碼。要特別注意return captchaProducer;與private Producer captchaProducer = null;中captchaProducer名字要一樣,不然就加載不到這個bean。
2、測試:
輸入正確的驗證碼:
驗證通過
輸入錯誤的驗證碼
驗證未通過
為了說明兩次的驗證碼是基于兩種方式生成的,方式一和方式二的驗證碼我設(shè)置了不同的屬性,從圖片中可以看出兩次驗證碼的顏色、干擾線、背景等都有不同。
總結(jié):
1、過程梳理:
不論是哪種方式,都是先把kaptcha加入spring容器,即要有一個kaptcha的bean;再新建一個controller,把kaptcha的bean注入到controller中用于生成驗證碼;然后需要有一個比對驗證碼的工具類,在測試的controller中調(diào)用工具類進行驗證碼比對;最后在前端頁面只需要用一個<img src = "/生成驗證碼的controller的路由">
即可獲取驗證碼,通過給這個img標簽加點擊事件就可實現(xiàn)“點擊切換驗證碼”。
2、與spring整合kaptcha對比
spring整合kaptcha也介紹了兩種方式,在web.xml中配置最簡潔,不需要寫生成驗證碼的controller,在頁面中直接用src指向web.xml中kaptcha的servlet 的<url-pattern >的值即可。
springboot整合kaptcha的兩種方式都類似于spring整合kaptcha的第二種方式,都是先配置bean,然后用controller生成驗證碼,前端用src指向這個controller,不同之處在于:假如生成驗證碼的controller路由為/xxx,那么spring 整合kaptcha時src = “xxx.jpg”,springboot整合kaptcha時src = "/xxx"。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- SpringBoot+kaptcha實現(xiàn)圖片驗證碼功能詳解
- SpringBoot整合kaptcha實現(xiàn)圖片驗證碼功能
- Springboot?+redis+谷歌開源Kaptcha實現(xiàn)圖片驗證碼功能
- SpringBoot集成Kaptcha驗證碼的詳細過程
- SpringBoot使用Kaptcha實現(xiàn)驗證碼的生成與驗證功能
- SpringBoot+kaptcha實現(xiàn)驗證碼花式玩法詳解
- Google Kaptcha 框架實現(xiàn)登錄驗證碼功能(SSM 和 SpringBoot)
- SpringBoot 集成Kaptcha實現(xiàn)驗證碼功能實例詳解
- SpringBoot整合Kaptcha實現(xiàn)圖片驗證碼加減乘除功能
相關(guān)文章
MybatisPlus lambdaQueryWrapper中常用方法的使用
本文主要介紹了MybatisPlus lambdaQueryWrapper中常用方法的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-07-07Java日期格式化的實現(xiàn)(@JsonFormat和@JSONField)
本文主要介紹了Java日期格式化的實現(xiàn),主要介紹了@JsonFormat和@JSONField兩種方式,具有一定的參考價值,感興趣的可以了解一下2024-05-05Mybatis?大數(shù)據(jù)量批量寫優(yōu)化的案例詳解
這篇文章主要介紹了Mybatis?大數(shù)據(jù)量批量寫優(yōu)化的示例代碼,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-05-05mybatis?mapper.xml中如何根據(jù)數(shù)據(jù)庫類型選擇對應SQL語句
這篇文章主要介紹了mybatis?mapper.xml中如何根據(jù)數(shù)據(jù)庫類型選擇對應SQL語句,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01詳解SpringMVC中設(shè)置靜態(tài)資源不被攔截的問題
這篇文章主要介紹了詳解SpringMVC中設(shè)置靜態(tài)資源不被攔截的問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02Java實現(xiàn)InputStream的任意拷貝方式
這篇文章主要介紹了Java實現(xiàn)InputStream的任意拷貝方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10java 定時同步數(shù)據(jù)的任務優(yōu)化
這篇文章主要介紹了java 定時同步數(shù)據(jù)的任務優(yōu)化,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-12-12