java 實現登錄驗證碼 (kaptcha 驗證碼組件)


博客地址:https://ainyi.com/70

驗證碼的作用:

1、防止廣告機注冊和發帖、評論。
2、防止暴力破解密碼,特別是有管理員權限的密碼。

在這里介紹一種非常實用的驗證碼生成工具:kaptcha 

這個工具,可以生成各種樣式的驗證碼,因為它是可配置的。

而 kaptcha工作的原理,是調用 com.google.code.kaptcha.servlet.KaptchaServlet,生成一個圖片。同時將生成的驗證碼字符串放到 HttpSession中,直接從session中獲取這張驗證碼圖片,而不會占用實際內存。

使用 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
kaptcha.session.key           session中存放驗證碼的key鍵

 

所實用的框架:SSM

所需的驗證碼的 jar 包:kaptcha-2.3.2.jar,可以到官網上下載:http://code.google.com/p/kaptcha/

applicationContext.xml 需要配置驗證碼的相關屬性:

 1 <!-- 驗證碼 -->
 2     <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
 3         <property name="config">
 4             <bean class="com.google.code.kaptcha.util.Config">
 5                 <constructor-arg>
 6                     <props>
 7                         <!--這里的顏色只支持標准色和rgb顏色,不可使用十六進制的顏色-->
 8                         <!-- 是否有邊框 -->
 9                         <prop key="kaptcha.border">no</prop>
10                         <!-- 驗證碼文本字符顏色 -->
11                         <prop key="kaptcha.textproducer.font.color">black</prop>
12                         <!-- 驗證碼圖片寬度 -->
13                         <prop key="kaptcha.image.width">92</prop>
14                         <!-- 驗證碼圖片高度 -->
15                         <prop key="kaptcha.image.height">36</prop>
16                         <!-- 驗證碼文本字符大小 -->
17                         <prop key="kaptcha.textproducer.font.size">24</prop>
18                         <!-- session中存放驗證碼的key鍵 -->
19                         <prop key="kaptcha.session.key">code</prop>
20                         <!-- 驗證碼噪點顏色 -->
21                         <prop key="kaptcha.noise.color">white</prop>
22                         <!-- 驗證碼文本字符間距 -->
23                         <prop key="kaptcha.textproducer.char.space">3</prop>
24                         <!-- 驗證碼樣式引擎 -->
25                         <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.ShadowGimpy</prop>
26                         <!-- 驗證碼文本字符長度 -->
27                         <prop key="kaptcha.textproducer.char.length">4</prop>
28                         <!-- 驗證碼文本字體樣式 -->
29                         <prop key="kaptcha.textproducer.font.names">宋體,楷體,微軟雅黑</prop>
30                     </props>
31                 </constructor-arg>
32             </bean>
33         </property>
34     </bean>

 

生成二維碼圖片的控制類:CaptchaController.java

 1 /**
 2      * com.krry.web 
 3      * 方法名:生成二維碼控制類
 4      * 創建人:krry 
 5      * @param request
 6      * @param response
 7      * @return
 8      * @throws Exception 
 9      * 返回類型:ModelAndView
10      * @exception 
11      * @since  1.0.0
12     */
13     @RequestMapping("/code")
14     public ModelAndView getKaptchaImage(HttpServletRequest request,HttpServletResponse response) throws Exception {
15         HttpSession session = request.getSession();
16         //獲取驗證碼
17         //    String code = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
18         //    String code = (String) session.getAttribute("Kaptcha_Code");
19         //清除瀏覽器的緩存
20         response.setDateHeader("Expires", 0);
21         // Set standard HTTP/1.1 no-cache headers.
22         response.setHeader("Cache-Control","no-store, no-cache, must-revalidate");
23         // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
24         response.addHeader("Cache-Control", "post-check=0, pre-check=0");
25         // Set standard HTTP/1.0 no-cache header.
26         response.setHeader("Pragma", "no-cache");
27         // return a jpeg
28         response.setContentType("image/jpeg");
29         //瀏覽器記憶功能-----當前過瀏覽器和服務器交互成功以后下載的圖片和資源會進行緩存一次。下次刷新的時候就不會在到服務器去下載。
30         // 獲取KAPTCHA驗證的隨機文本
31         String capText = captchaProducer.createText();
32         // 將生成好的圖片放入會話中
33         session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
34         // create the image with the text
35         BufferedImage bi = captchaProducer.createImage(capText);
36         ServletOutputStream out = response.getOutputStream();
37         // write the data out
38         ImageIO.write(bi, "jpg", out);
39         try {
40             out.flush();
41         } finally {
42             out.close();//關閉
43         }
44         return null;
45     }

 

前台調用:

1 <input type='text' placeholder='請輸入驗證碼...' maxlength='4' autocomplete='off' class='inp kr_code' id='code'/>
2 <img src='"+basePath+"/kaptcha/code.do' class='yanz_img' onclick='changeyanz($(this));'>

 

js方法:

點擊驗證碼圖片換驗證碼時,<img> 的 onclick 里面做的就是改變 <img> 標簽的 src 屬性。

所以要給 url 帶一個隨機數,這樣每次點擊驗證碼圖片時,都會由於 src 改變而重新請求 jsp

1 function changeyanz(obj){
2     obj.attr("src",basePath+"/kaptcha/code.do?d="+new Date().getTime());
3 }

 

登錄時對驗證碼的驗證:LoginController.java

 1         //獲取用戶傳遞進來的驗證碼
 2         String code = request.getParameter("code");
 3         if(TmStringUtils.isNotEmpty(code)){
 4             //獲取session中的驗證碼
 5             String sessionCode = (String)request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
 6             //如果輸入的驗證碼和會話的驗證碼不一致的,提示用戶輸入有誤
 7             if(TmStringUtils.isNotEmpty(sessionCode) && !code.equalsIgnoreCase(sessionCode)){
 8                 return "error_code";
 9             }
10         }

 

以上配置的效果圖:

 

博客地址:https://ainyi.com/70

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM