Spring MVC Captcha 验证码

本文专为不想一遍遍手写验证码代码的”懒猿“而生,只需要添加部分配置文件,拷贝一个控制层代码,就能在页面中方便使用。话不多说,进入主题:

一. Spring MVC 环境实现方式:

1.1 spring-mvc.xml 

  1. <!--kaptcha登录验证码 -->  
  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.                     <prop key="kaptcha.border">no</prop>  
  8.                     <prop key="kaptcha.border.color">105,179,90</prop>  
  9.                     <prop key="kaptcha.textproducer.font.color">red</prop>  
  10.                     <prop key="kaptcha.image.width">200</prop>  
  11.                     <prop key="kaptcha.textproducer.font.size">48</prop>  
  12.                     <prop key="kaptcha.image.height">48</prop>  
  13.                     <prop key="kaptcha.session.key">code</prop>  
  14.                     <prop key="kaptcha.textproducer.char.string">123456789</prop>  
  15.                     <prop key="kaptcha.textproducer.char.length">4</prop>  
  16.                     <prop key="kaptcha.textproducer.char.space">6</prop>  
  17.                     <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>  
  18.                     <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.WaterRipple</prop>  
  19.                 </props>  
  20.             </constructor-arg>  
  21.         </bean>  
  22.     </property>  
  23. </bean>  

1.2 Controller 实现

 

 
  1. package com.vopzoon.app.base.captcha;  
  2.   
  3. import java.awt.image.BufferedImage;  
  4.   
  5. import javax.imageio.ImageIO;  
  6. import javax.servlet.ServletOutputStream;  
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9. import javax.servlet.http.HttpSession;  
  10.   
  11. import org.springframework.beans.factory.annotation.Autowired;  
  12. import org.springframework.stereotype.Controller;  
  13. import org.springframework.web.bind.annotation.RequestMapping;  
  14. import org.springframework.web.servlet.ModelAndView;  
  15.   
  16. import com.google.code.kaptcha.Constants;  
  17. import com.google.code.kaptcha.Producer;  
  18.   
  19. /** 
  20.  * 防止Captcha机器人登陆 
  21.  * @author liuwang 
  22.  * 
  23.  */  
  24. @Controller  
  25. @RequestMapping("/kaptcha/*")  
  26. public class CaptchaController {  
  27.       
  28.     @Autowired  
  29.     private Producer captchaProducer = null;  
  30.   
  31.     @RequestMapping  
  32.     public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {  
  33.         HttpSession session = request.getSession();  
  34.         String code = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);  
  35.         System.out.println("******************验证码是: " + code + "******************");  
  36.           
  37.         response.setDateHeader("Expires", 0);  
  38.           
  39.         // Set standard HTTP/1.1 no-cache headers.  
  40.         response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
  41.           
  42.         // Set IE extended HTTP/1.1 no-cache headers (use addHeader).  
  43.         response.addHeader("Cache-Control", "post-check=0, pre-check=0");  
  44.           
  45.         // Set standard HTTP/1.0 no-cache header.  
  46.         response.setHeader("Pragma", "no-cache");  
  47.           
  48.         // return a jpeg  
  49.         response.setContentType("image/jpeg");  
  50.           
  51.         // create the text for the image  
  52.         String capText = captchaProducer.createText();  
  53.           
  54.         // store the text in the session  
  55.         session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);  
  56.           
  57.         // create the image with the text  
  58.         BufferedImage bi = captchaProducer.createImage(capText);  
  59.         ServletOutputStream out = response.getOutputStream();  
  60.           
  61.         // write the data out  
  62.         ImageIO.write(bi, "jpg", out);  
  63.         try {  
  64.             out.flush();  
  65.         } finally {  
  66.             out.close();  
  67.         }  
  68.         return null;  
  69.     }  
  70.   
  71. }  


3. JSP 代码

 

 
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. <script type="text/javascript" src="js/jquery.js"></script>  
  8. <script type="text/javascript" src="js/functions.js"></script>  
  9.   
  10. <title>测试页面</title>  
  11. <script type="text/javascript">  
  12. $(function(){         
  13.     $('#kaptchaImage').click(function () {//生成验证码  
  14.      $(this).hide().attr('src', './kaptcha/getKaptchaImage.do?' + Math.floor(Math.random()*100) ).fadeIn();  
  15.      event.cancelBubble=true;  
  16.     });  
  17. });   
  18.   
  19. window.onbeforeunload = function(){  
  20.     //关闭窗口时自动退出  
  21.     if(event.clientX>360&&event.clientY<0||event.altKey){     
  22.         alert(parent.document.location);  
  23.     }  
  24. };  
  25.   
  26. function changeCode() {  
  27.     $('#kaptchaImage').hide().attr('src', './kaptcha/getKaptchaImage.do?' + Math.floor(Math.random()*100) ).fadeIn();  
  28.     event.cancelBubble=true;  
  29. }  
  30. </script>  
  31. </head>  
  32. <body>  
  33.           
  34. <div class="chknumber">  
  35.       <label>验证码:  
  36.       <input name="kaptcha" type="text" id="kaptcha" maxlength="4" class="chknumber_input" />               
  37.       </label>  
  38.       <br />  
  39.       <img src="./kaptcha/getKaptchaImage.do" id="kaptchaImage"  style="margin-bottom: -3px"/>  
  40.       <href="#" onclick="changeCode()">看不清?换一张</a>  
  41. </div>  
  42. </body>  
  43. </html>  


PS:需要自行引入kaptcha.jar;

 

二:servlet实现方式

2.1 web.xml 配置:

 

 
    1. <!--Kaptcha 验证码  -->  
    2.     <servlet>  
    3.         <!-- 生成验证码和刷新的Servlet -->  
    4.         <servlet-name>kaptcha</servlet-name>  
    5.         <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>  
    6.         <init-param>  
    7.             <!-- 验证码图片的边框 yes和no -->  
    8.             <param-name>kaptcha.border</param-name>  
    9.             <param-value>yes</param-value>  
    10.         </init-param>  
    11.         <init-param>  
    12.             <!-- 验证码图片的边框的颜色 -->  
    13.             <param-name>kaptcha.border.color</param-name>  
    14.             <param-value>105,179,90</param-value>  
    15.         </init-param>       
    16.         <init-param>  
    17.             <!-- 验证码的颜色 -->  
    18.             <param-name>kaptcha.textproducer.font.color</param-name>  
    19.             <param-value>red</param-value>  
    20.         </init-param>  
    21.         <init-param>  
    22.             <!-- 整个验证码在图片中的宽度 -->  
    23.             <param-name>kaptcha.image.width</param-name>  
    24.             <param-value>250</param-value>  
    25.         </init-param>  
    26.         <init-param>  
    27.             <!-- 整个验证码在图片中的高度 -->  
    28.             <param-name>kaptcha.image.height</param-name>  
    29.             <param-value>90</param-value>  
    30.         </init-param>  
    31.         <init-param>  
    32.             <!-- 验证码在图片中的大小 -->  
    33.             <param-name>kaptcha.textproducer.font.size</param-name>  
    34.             <param-value>70</param-value>  
    35.         </init-param>  
    36.         <init-param>  
    37.             <!-- 获取验证码的名字SESSION -->  
    38.             <param-name>kaptcha.session.key</param-name>  
    39.             <param-value>code</param-value>  
    40.         </init-param>  
    41.         <init-param>  
    42.             <!-- 显示几个验证码 -->  
    43.             <param-name>kaptcha.textproducer.char.length</param-name>  
    44.             <param-value>4</param-value>  
    45.         </init-param>  
    46.         <init-param>  
    47.             <!-- 验证码的字体和式样 -->  
    48.             <param-name>kaptcha.textproducer.font.names</param-name>  
    49.             <param-value>宋体,楷体,微软雅黑</param-value>  
    50.         </init-param>       
    51.     </servlet>  
    52.   
    53.     <servlet-mapping>  
    54.         <servlet-name>kaptcha</servlet-name>  
    55.         <url-pattern>/kaptcha/kaptcha.jpg</url-pattern>  
    56.     </servlet-mapping>  
posted @ 2018-03-16 10:24  youqc  阅读(256)  评论(0编辑  收藏  举报