一、kaptcha 的簡介
kaptcha 是一個非常實用的驗證碼生成工具。有了它,你可以生成各種樣式的驗證碼,因為它是可配置的。kaptcha工作的原理是調用 com.google.code.kaptcha.servlet.KaptchaServlet,生成一個圖片。
同時將生成的驗證碼字符串放到 HttpSession中。
使用kaptcha可以方便的配置:
- 驗證碼的字體
- 驗證碼字體的大小
- 驗證碼字體的字體顏色
- 驗證碼內容的范圍(數字,字母,中文漢字!)
- 驗證碼圖片的大小,邊框,邊框粗細,邊框顏色
- 驗證碼的干擾線(可以自己繼承com.google.code.kaptcha.NoiseProducer寫一個自定義的干擾線)
- 驗證碼的樣式(魚眼樣式、3D、普通模糊……當然也可以繼承com.google.code.kaptcha.GimpyEngine自定義樣式)
二、生成驗證碼的案例
下面介紹一下用法:
1. 下載該依賴包
方式一:首先去官網下載jar:http://code.google.com/p/kaptcha/
建立一個web項目,導入 kaptcha-2.3.jar 到環境變量中。
方式二:網盤下載jar包: http://yunpan.cn/cdjzkrjKgQ7eD 訪問密碼 754f
沒有翻牆的同學可以通過該路徑下載。
2. 新建一個java web項目 SpringKaptcha ,並配置好Spring的環境。
可以參考:
基於XML配置的Spring MVC 簡單的HelloWorld實例應用
基於注解配置的Spring MVC 簡單的HelloWorld實例應用
spring-mvc.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" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <context:component-scan base-package="com.souvc.controller"/> <mvc:annotation-driven/> <!-- 定義視圖解析器ViewResolver --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
web.xml 配置文件:

<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <!-- 指定Spring的配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.form</url-pattern> </servlet-mapping> <filter> <filter-name>encodingFilter</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
3. 我們專注於驗證碼的生成工作。
(1)在spring-mvc.xml 中添加以下的配置。
<!-- 頁面生成隨機驗證碼 --> <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha"> <property name="config"> <bean class="com.google.code.kaptcha.util.Config"> <constructor-arg> <props> <prop key="kaptcha.border">no</prop> <prop key="kaptcha.border.color">105,179,90</prop> <prop key="kaptcha.textproducer.font.color">red</prop> <prop key="kaptcha.image.width">250</prop> <prop key="kaptcha.textproducer.font.size">80</prop> <prop key="kaptcha.image.height">90</prop> <prop key="kaptcha.session.key">code</prop> <prop key="kaptcha.textproducer.char.length">4</prop> <prop key="kaptcha.textproducer.font.names">宋體,楷體,微軟雅黑</prop> </props> </constructor-arg> </bean> </property> </bean>
(2)添加 生成驗證碼的 controller。
package com.souvc.app.base.captcha; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.google.code.kaptcha.Constants; import com.google.code.kaptcha.Producer; /** * 防止Captcha機器人登陸 * @author liuwang * */ @Controller @RequestMapping("/kaptcha/*") public class CaptchaController { @Autowired private Producer captchaProducer = null; @RequestMapping public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); String code = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY); System.out.println("******************驗證碼是: " + code + "******************"); response.setDateHeader("Expires", 0); // Set standard HTTP/1.1 no-cache headers. response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // Set IE extended HTTP/1.1 no-cache headers (use addHeader). response.addHeader("Cache-Control", "post-check=0, pre-check=0"); // Set standard HTTP/1.0 no-cache header. response.setHeader("Pragma", "no-cache"); // return a jpeg response.setContentType("image/jpeg"); // create the text for the image String capText = captchaProducer.createText(); // store the text in the session session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText); // create the image with the text BufferedImage bi = captchaProducer.createImage(capText); ServletOutputStream out = response.getOutputStream(); // write the data out ImageIO.write(bi, "jpg", out); try { out.flush(); } finally { out.close(); } return null; } }
(3)jsp代碼
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/functions.js"></script> <title>測試頁面</title> <script type="text/javascript"> $(function(){ $('#kaptchaImage').click(function () {//生成驗證碼 $(this).hide().attr('src', './kaptcha/getKaptchaImage.do?' + Math.floor(Math.random()*100) ).fadeIn(); event.cancelBubble=true; }); }); window.onbeforeunload = function(){ //關閉窗口時自動退出 if(event.clientX>360&&event.clientY<0||event.altKey){ alert(parent.document.location); } }; function changeCode() { $('#kaptchaImage').hide().attr('src', './kaptcha/getKaptchaImage.do?' + Math.floor(Math.random()*100) ).fadeIn(); event.cancelBubble=true; } </script> </head> <body> <div class="chknumber"> <label>驗證碼: <input name="kaptcha" type="text" id="kaptcha" maxlength="4" class="chknumber_input" /> </label> <br /> <img src="./kaptcha/getKaptchaImage.do" id="kaptchaImage" style="margin-bottom: -3px"/> <a href="#" onclick="changeCode()">看不清?換一張</a> </div> </body> </html>
簡潔jsp 版本:
<div class="lr-formWrap"> <input type="text" class="lr-input" placeholder="請輸入圖片驗證碼" style="width:145px;padding-left:15px" id="imageCode" name="imageCode" value=""> <div class="fn-right"> <img id="randImage" border="0" align="absmiddle" src="${basePath }/captcha-image" name="randImage" alt="驗證碼" width="115px" height="39px"/> </div> <p class="lr-tip" id="imageCode-lr-tip"></p> </div>
簡潔js版本 :
//生成驗證碼
$('#randImage').click(function () {
$(this).hide().attr('src', '${basePath}/captcha-image?' + Math.floor(Math.random()*100) ).fadeIn();
});
//刷新后,生成驗證碼
$('#refreshCode').click(function () {
$('#randImage').hide().attr('src', '${basePath}/captcha-image?' + Math.floor(Math.random()*100) ).fadeIn();
});
溫馨提示:
獲取驗證碼的關鍵語句,如下:
String code =(String)session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
(4) kaptcha可配置項
kaptcha.border 是否有邊框 默認為true 我們可以自己設置yes,no kaptcha.border.color 邊框顏色 默認為Color.BLACK kaptcha.border.thickness 邊框粗細度 默認為1 kaptcha.producer.impl 驗證碼生成器 默認為DefaultKaptcha kaptcha.textproducer.impl 驗證碼文本生成器 默認為DefaultTextCreator kaptcha.textproducer.char.string 驗證碼文本字符內容范圍 默認為abcde2345678gfynmnpwx kaptcha.textproducer.char.length 驗證碼文本字符長度 默認為5 kaptcha.textproducer.font.names 驗證碼文本字體樣式 默認為new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize) kaptcha.textproducer.font.size 驗證碼文本字符大小 默認為40 kaptcha.textproducer.font.color 驗證碼文本字符顏色 默認為Color.BLACK kaptcha.textproducer.char.space 驗證碼文本字符間距 默認為2 kaptcha.noise.impl 驗證碼噪點生成對象 默認為DefaultNoise kaptcha.noise.color 驗證碼噪點顏色 默認為Color.BLACK kaptcha.obscurificator.impl 驗證碼樣式引擎 默認為WaterRipple kaptcha.word.impl 驗證碼文本字符渲染 默認為DefaultWordRenderer kaptcha.background.impl 驗證碼背景生成器 默認為DefaultBackground kaptcha.background.clear.from 驗證碼背景顏色漸進 默認為Color.LIGHT_GRAY kaptcha.background.clear.to 驗證碼背景顏色漸進 默認為Color.WHITE kaptcha.image.width 驗證碼圖片寬度 默認為200 kaptcha.image.height 驗證碼圖片高度 默認為50
(6)驗證驗證碼是否正確的方法:
@RequestMapping(value = "/checkRandCode", method = RequestMethod.GET) public void checkRandCode(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> map = new HashMap<String, Object>(); try { String randCode = request.getParameter("randCode"); logger.info("randCode: " +randCode); String status = "0"; String code = (String)request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); if(randCode.toLowerCase().equals(code.toLowerCase()))status="1"; map.put("status", status); map.put("description", ""); String data = JSONObject.fromObject(map).toString(); logger.info("返回給頁面的數據為: " + data); response.getWriter().print(data); response.getWriter().flush(); response.getWriter().close(); } catch (Exception ex) { logger.error(ex.getMessage(), ex); }
(7) 默認值