驗證碼(CAPTCHA)是“Completely Automated Public Turing test to tell Computers and Humans Apart”(全自動區分計算機和人類的圖靈測試)的縮寫,是一種區分用戶是計算機還是人的公共全自動程序。可以防止:惡意破解密碼、刷票、論壇灌水,有效防止某個黑客對某一個特定注冊用戶用特定程序暴力破解方式進行不斷的登陸嘗試,實際上用驗證碼是現在很多網站通行的方式,我們利用比較簡易的方式實現了這個功能。今天給大家介紹一下kaptcha的和springboot一起使用的簡單例子。
准備工作
1.首要要有一個可以運行的springboot的項目並可以正常運行
2.導入kaptcha依賴
<!--驗證碼--> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
開始試驗
我們有兩種方式在springboot中使用kaptcha
1.使用.xml的配置方式配置生成kaptcha的bean對象,在啟動類上@ImportResource這個xml文件;在controller中注入其對象並使用
2.是把kaptcha作為工程的一個類,加上@component注解在返回kaptcha的方法中加上@Bean注解,再在controller中注入其對象。
第一種方法
在resources中創建一個kaptchaConfig.xml文件 如:
kaptchaConfig.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"> <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"> <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> <!--驗證碼保存在session的key--> <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> <!--干擾顏色,合法值: r,g,b 或者 white,black,blue.--> <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>
在springboot啟動類上引入這個文件
@SpringBootApplication @ImportResource(locations={"classpath:kaptchaConfig.xml"}) public class CodeDemoApplication { public static void main(String[] args) { SpringApplication.run(CodeDemoApplication.class, args); } }
在controller中注入DefaultKaptcha
@Autowired
DefaultKaptcha defaultKaptcha;
在controller中編寫獲取驗證碼圖片的方法
//獲取驗證碼 @RequestMapping("/getCode") public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{ byte[] captchaChallengeAsJpeg = null; ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); try { //生產驗證碼字符串並保存到session中 String createText = defaultKaptcha.createText(); httpServletRequest.getSession().setAttribute("vrifyCode", createText); //使用生產的驗證碼字符串返回一個BufferedImage對象並轉為byte寫入到byte數組中 BufferedImage challenge = defaultKaptcha.createImage(createText); ImageIO.write(challenge, "jpg", jpegOutputStream); } catch (IllegalArgumentException e) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } //定義response輸出類型為image/jpeg類型,使用response輸出流輸出圖片的byte數組 captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); httpServletResponse.setHeader("Cache-Control", "no-store"); httpServletResponse.setHeader("Pragma", "no-cache"); httpServletResponse.setDateHeader("Expires", 0); httpServletResponse.setContentType("image/jpeg"); ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream(); responseOutputStream.write(captchaChallengeAsJpeg); responseOutputStream.flush(); responseOutputStream.close(); }
在controller中編寫驗證的方法
//驗證碼驗證 @RequestMapping("/checkCode") @ResponseBody public boolean imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){ String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifyCode"); String parameter = httpServletRequest.getParameter("code"); log.info("Session vrifyCode ---->"+captchaId+"---- form code --->"+parameter); if (!captchaId.equals(parameter)) { log.info("錯誤的驗證碼"); return false; } else { return true; } }
模板頁面register.html
...... <div class="form-group"> <label class="col-md-2 col-md-offset-2 control-label">驗證碼</label> <div class="col-md-3"> <div class="row_bj" style="width:100%;"> <input type="text" class="form-control" id="code" name="code" required placeholder="請輸入驗證碼"> <img alt="驗證碼" onclick = "this.src='/getCode?d='+new Date()*1" src="/getCode" style="margin-left:20px;"/> </div> <label class="control-label text-danger" id="code2">(驗證碼錯誤)</label> </div> </div> ......
啟動訪問
控制台日志結果:
第二種方法:這種方法把.xml文件換成使用代碼來配置:
KaptchaConfig配置類:
@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", "no"); properties.setProperty("kaptcha.border.color", "105,179,90"); properties.setProperty("kaptcha.textproducer.font.color", "red"); properties.setProperty("kaptcha.image.width", "110"); properties.setProperty("kaptcha.image.height", "40"); properties.setProperty("kaptcha.textproducer.font.size", "40"); 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; } }
注意要去掉啟動類中引入的.xml文件,不然會有兩個相同的對象,而你沒有指明要注入哪一個的話啟動會失敗。
補充:對於kaptcha的配置屬性可以百度找一找。