springmvc 프로젝트 에서 kaptcha 를 사용 하여 인증 코드 를 생 성 합 니 다.

Kaptcha 인증번호
kaptcha-2.3.2.jar 다운로드
http://code.google.com/p/kaptcha/downloads/list
1.spring 프로필 applicationContext.xml
[html]
    
    <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.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 코드
<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.contrller 에서 입력 한 인증 코드 가 정확 한 지 검증 합 니 다.
[java] view plaincopyprint?
//   
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 설정 가능 항목
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

좋은 웹페이지 즐겨찾기