在springmvc項目中使用google kaptcha生成驗證碼

Kaptcha驗證碼javascript

下載kaptcha-2.3.2.jarjava

http://code.google.com/p/kaptcha/downloads/listjquery

1.spring 配置文件 applicationContext.xmlweb

<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的實現ajax

package com.controller.common;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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("/")  
public class CaptchaImageCreateController {
 
 private Producer captchaProducer = null;  
   
     @Autowired  
     public void setCaptchaProducer(Producer captchaProducer) {  
         this.captchaProducer = captchaProducer;  
     }  
   
     @RequestMapping("/captcha-image")  
     
     public ModelAndView handleRequest
    (HttpServletRequest request, HttpServletResponse response) throws Exception {  
   
         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 
 
         request.getSession().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代碼spring

<div class="title"> 用戶登陸 </div>
<div class="loginbox">
        
     <form id="loginForm" action="${pageContext.request.contextPath}/login" method="post">
          <div style="height:40px;">
              <label class="tip">登&nbsp;錄&nbsp;名:&nbsp;&nbsp; </label>
              <input name="name" type="text" id="name" class="user-text" value="" />
          </div>
          <div style="height:40px;">
               <label class="tip">密 &nbsp;&nbsp;碼:&nbsp;&nbsp;</label>
             <input type="password" id="password" name="password" class="user-text" value="" />
          </div>
          <div style="height:60px;">
               <label class="tip">驗&nbsp;證&nbsp;碼:&nbsp;&nbsp; </label>
               <input type="text" name="verifyCode" id="verifyCode" class="usertext" value=""                         onchange="changeVerifyCode();"/>
               <img src="captcha-image.jpg" width="110" height="30" id="kaptchaImage" 
                        style="margin-bottom: -13px"/> 
          </div>
          <div style="margin-left:15px">
             <input type="submit" class="login-btn" value="登陸" />
             <input type="reset"  class="login-btn" style="margin-left:10px;"  value="重置" />
          </div>
       </form>
          
</div>
//如下是js文件

<script type="text/javascript" src="static/js/jquery-1.9.1.js"></script>
<script type="text/javascript">
    $(function(){
        $('#kaptchaImage').click(function () { 
            $(this).attr('src', 'captcha-image.jpg?' + Math.floor(Math.random()*100) ); 
        })
    });
    //修改驗證碼觸發的函數 

    function  changeVerifyCode(){
     var verifyCodeValue = $("#verifyCode").val();
        if(verifyCodeValue.replace(/\s/g,"") == "") {
            alert("請輸入驗證碼");
        }else {
            //異步檢查驗證碼是否輸入正確

            var verifyUrl = "${pageContext.request.contextPath}/checkVerificationCode";
            $.ajax({
                type:"POST",
                url:verifyUrl,
                data:{"verifyCode":verifyCodeValue},
                success:function(data){
                    if(data==true) {
                     //驗證碼正確,進行提交操做

                     //alert("輸入正確 !");
                    }else {
                        alert("請輸入正確的驗證碼!");
                    }
                },
                error:function(e){
                    alert(e);
                }
            });
        }
    }
</script>


4.controller中取得校驗碼驗證輸入的驗證碼是否正確session

//驗證碼
package com.controller.common;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class VerifyController {
 
 @RequestMapping(value = "checkVerificationCode")
    @ResponseBody
    public boolean checkVerificationCode(@RequestParam("verifyCode")String verifyCode,
       HttpServletRequest request){
        String kaptchaExpected = (String)request.getSession()
               .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        String kaptchaReceived = verifyCode;
        if  (kaptchaReceived == null  || !kaptchaReceived.equalsIgnoreCase(kaptchaExpected))
         {
                return false;
         }
         return true;
      }
 }

5.kaptcha可配置項app

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

 

Constant 描述 默認值
kaptcha.border 圖片邊框,合法值:yes , no yes
kaptcha.border.color 邊框顏色,合法值: r,g,b (and optional alpha) 或者 white,black,blue. black
kaptcha.border.thickness 邊框厚度,合法值:>0 1
kaptcha.image.width 圖片寬 200
kaptcha.image.height 圖片高 50
kaptcha.producer.impl 圖片實現類 com.google.code.kaptcha.impl.DefaultKaptcha
kaptcha.textproducer.impl 文本實現類 com.google.code.kaptcha.text.impl.DefaultTextCreator
kaptcha.textproducer.char.string 文本集合,驗證碼值今後集合中獲取 abcde2345678gfynmnpwx
kaptcha.textproducer.char.length 驗證碼長度 5
kaptcha.textproducer.font.names 字體 Arial, Courier
kaptcha.textproducer.font.size 字體大小 40px.
kaptcha.textproducer.font.color 字體顏色,合法值: r,g,b  或者 white,black,blue. black
kaptcha.textproducer.char.space 文字間隔 2
kaptcha.noise.impl 干擾實現類 com.google.code.kaptcha.impl.DefaultNoise
kaptcha.noise.color 干擾顏色,合法值: r,g,b 或者 white,black,blue. black
kaptcha.obscurificator.impl 圖片樣式:
水紋com.google.code.kaptcha.impl.WaterRipple
魚眼com.google.code.kaptcha.impl.FishEyeGimpy
陰影com.google.code.kaptcha.impl.ShadowGimpy
com.google.code.kaptcha.impl.WaterRipple
kaptcha.background.impl 背景實現類 com.google.code.kaptcha.impl.DefaultBackground
kaptcha.background.clear.from 背景顏色漸變,開始顏色 light grey
kaptcha.background.clear.to 背景顏色漸變,結束顏色 white
kaptcha.word.impl 文字渲染器 com.google.code.kaptcha.text.impl.DefaultWordRenderer
kaptcha.session.key session key KAPTCHA_SESSION_KEY
kaptcha.session.date session date KAPTCHA_SESSION_DA
相關文章
相關標籤/搜索