生成驗證碼的方式有不少,我的認爲較爲靈活方便的是Kaptcha ,他是基於SimpleCaptcha的開源項目。使用Kaptcha 生成驗證碼十分簡單而且參數能夠進行自定義。只需添加jar包配置下就可使用。kaptcha全部配置均可以經過web.xml來完成,若是項目使用了Spring MVC,那麼實現方式會略有不一樣。javascript
1、Servlet項目java
一、添加jar包依賴web
maven項目,在pom.xml中添加dependencyspring
<!-- kaptcha --> <dependency> <groupId>com.google.code.kaptcha</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
非maven項目,在官網下載kaptcha的jar包,而後添加到項目lib庫中。session
下載地址:http://code.google.com/p/kaptcha/downloads/listmvc
二、配置web.xmlapp
<servlet> <servlet-name>Kaptcha</servlet-name> <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Kaptcha</servlet-name> <url-pattern>/kaptcha.jpg</url-pattern> </servlet-mapping>
注:url-pattern 自定義dom
kaptcha的參數都有默認值,若是要配置kaptcha,在init-param增長響應的參數便可jsp
<servlet> <servlet-name>Kaptcha</servlet-name> <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> <init-param> <param-name>kaptcha.image.width</param-name> <param-value>200</param-value> <description>Width in pixels of the kaptcha image.</description> </init-param> <init-param> <param-name>kaptcha.image.height</param-name> <param-value>50</param-value> <description>Height in pixels of the kaptcha image.</description> </init-param> <init-param> <param-name>kaptcha.textproducer.char.length</param-name> <param-value>4</param-value> <description>The number of characters to display.</description> </init-param> <init-param> <param-name>kaptcha.noise.impl</param-name> <param-value>com.google.code.kaptcha.impl.NoNoise</param-value> <description>The noise producer.</description> </init-param> </servlet>
三、jsp代碼maven
<script type="text/javascript"> $(function(){ //生成驗證碼 $('#kaptchaImage').click(function () { $(this).hide().attr('src', '/code/captcha-image?' + Math.floor(Math.random()*100) ).fadeIn(); }); }); window.onbeforeunload = function(){ //關閉窗口時自動退出 if(event.clientX>360&&event.clientY<0||event.altKey){ alert(parent.document.location); } }; function changeCode() { //刷新 $('#kaptchaImage').hide().attr('src', '/code/captcha-image?' + Math.floor(Math.random()*100) ).fadeIn(); event.cancelBubble=true; } </script> <div class="form-group"> <label>驗證碼 </label> <input name="j_code" type="text" id="kaptcha" maxlength="4" class="form-control" /> <br/> <img src="/code/captcha-image" id="kaptchaImage" style="margin-bottom: -3px"/> <a href="#" onclick="changeCode()">看不清?換一張</a> </div>
2、Spring mvc 中使用kaptcha
一、spring 配置文件 applicationContext.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">yes</prop> <prop key="kaptcha.border.color">105,179,90</prop> <prop key="kaptcha.textproducer.font.color">blue</prop> <prop key="kaptcha.image.width">125</prop> <prop key="kaptcha.image.height">45</prop> <prop key="kaptcha.textproducer.font.size">45</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>
二、Controller的實現
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; @Controller @RequestMapping("/code") public class CaptchaController { @Autowired private Producer captchaProducer = null; @RequestMapping(value = "captcha-image") 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); 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(); } return null; } }
三、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