1. 程式人生 > >驗證碼-Jcaptcha的使用

驗證碼-Jcaptcha的使用

nal tin size 高度 mage () info uart true

pom.xml引入依賴

<dependency>  
        <groupId>com.octo.captcha</groupId>  
        <artifactId>jcaptcha-all</artifactId>  
        <version>1.0-RC6</version>  
        <exclusions>  
            <exclusion>  
                <groupId>quartz</groupId
> <artifactId>quartz</artifactId> </exclusion> <exclusion> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> </exclusion> <
exclusion> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> </exclusion> <exclusion> <groupId>hsqldb</groupId> <artifactId>
hsqldb</artifactId> </exclusion> <exclusion> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </exclusion> <exclusion> <groupId>concurrent</groupId> <artifactId>concurrent</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </exclusion> <exclusion> <groupId>xerces</groupId> <artifactId>xercesImpl</artifactId> </exclusion> <exclusion> <groupId>xerces</groupId> <artifactId>xmlParserAPIs</artifactId> </exclusion> </exclusions> </dependency>

定義驗證碼使用的服務類(這裏使用單例定義該服務類):

package com.trustel.common;

import java.awt.Color;
import java.awt.Font;

import com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator;
import com.octo.captcha.component.image.backgroundgenerator.UniColorBackgroundGenerator;
import com.octo.captcha.component.image.fontgenerator.RandomFontGenerator;
import com.octo.captcha.component.image.textpaster.RandomTextPaster;
import com.octo.captcha.component.image.wordtoimage.ComposedWordToImage;
import com.octo.captcha.component.word.FileDictionary;
import com.octo.captcha.component.word.wordgenerator.ComposeDictionaryWordGenerator;
import com.octo.captcha.engine.GenericCaptchaEngine;
import com.octo.captcha.image.gimpy.GimpyFactory;
import com.octo.captcha.service.multitype.GenericManageableCaptchaService;


public class CaptchaUtil{
    private static GenericManageableCaptchaService imageCaptchaService = null;
    
    public static GenericManageableCaptchaService getInstance(){
        if(imageCaptchaService == null){
            imageCaptchaService = generateImageCaptchaService();
        }
        return imageCaptchaService;
    }
    
    public static GenericManageableCaptchaService generateImageCaptchaService(){
        Integer WIDTH = 60;//驗證碼寬
        Integer HEIGHT = 25;//驗證碼高
        Integer MINLENGTH = 4;//字符最短
        Integer MAXLENGTH = 4;//字符最長
        Integer MINFONTSIZE = 10;//字符最小
        Integer MAXFONTSIZE = 15;//字符最大
        Integer LIVETIME = 5*60;//驗證碼存活時間
        Integer MAXCAPTCHASTORESIZE = 200000;//最大存儲大小
        //隨機顏色
//        RandomRangeColorGenerator textColor = new RandomRangeColorGenerator(new int[]{0,0},new int[]{0,0},new int[]{0,0},new int[]{255,255});
        //驗證碼字符
//        RandomTextPaster randomTextPaster = new RandomTextPaster(MINLENGTH, MAXLENGTH, textColor,true);
        RandomTextPaster randomTextPaster = new RandomTextPaster(MINLENGTH, MAXLENGTH, Color.gray);

        //背景(漸變色)
//        BackgroundGenerator colorbgGen = new GradientBackgroundGenerator(WIDTH, HEIGHT,new Color(46,195,231),Color.WHITE);
         //背景大小及樣式設置,UniColorBackgroundGenerator類生成的是統一背景,這裏背景統一是lightGray顏色 
          //寬度為180,高度為50。 
          BackgroundGenerator colorbgGen = new UniColorBackgroundGenerator(WIDTH, HEIGHT);
         /* //FunkyBackgroundGenerator類生成的是炫酷背景 
          BackgroundGenerator back = new  FunkyBackgroundGenerator(new Integer( 
            180), new Integer(50));*/  
        
        //隨機生成的字體大小和字體類型
        RandomFontGenerator randomFontGenerator = new RandomFontGenerator(MINFONTSIZE, MAXFONTSIZE, new Font[]{new Font("Arial", 0, 10),new Font("Tahoma",0,10)});
        //生成圖片對象
        ComposedWordToImage cwti = new ComposedWordToImage(randomFontGenerator,colorbgGen,randomTextPaster);
        //隨機文本的字典
        ComposeDictionaryWordGenerator cdwg = new ComposeDictionaryWordGenerator(new FileDictionary("toddlist"));
        GimpyFactory gf = new GimpyFactory(cdwg, cwti);
        
        GenericCaptchaEngine gce = new GenericCaptchaEngine(new GimpyFactory[]{gf});
        //返回一個對象,
        return new GenericManageableCaptchaService(gce, LIVETIME, MAXCAPTCHASTORESIZE);
    }
    
    public static Boolean validateCaptcha(String id,String captcha){
        boolean isValid = false;
        isValid = getInstance().validateResponseForID(id, captcha).booleanValue();
        return isValid;
    }
    
}

產生驗證碼:

如果是spring的話,在controller中定義產生驗證碼的方法:

@GetMapping("/captcha")
    public void getCaptcha(HttpServletRequest request,HttpServletResponse response){
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        
        BufferedImage bi = CaptchaUtil.getInstance().getImageChallengeForID(request.getSession(true).getId());
        try {
            ServletOutputStream out = response.getOutputStream();
            ImageIO.write(bi, "jpg", out);
            try{
                out.flush();
            }finally{
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }

在前端頁面定義驗證碼產生的位置

...
<input id="yzm" type="text" maxlength="4" name="captcha" placeholder="驗證碼">
<img id="captcha" class="code-pic" style="cursor: pointer;" alt="驗證碼" src="<%=basePath %>/sys/captcha">
...
<script type="text/javascript">
$("#captcha").bind(click,function(){
    $("#captcha").prop("src",<%=basePath %>/sys/captcha);
})
</script>

檢驗驗證碼:

...
String captchaValue= request.getParameter("captcha");//request獲得驗證碼
Boolean isValid=CaptchaUtil.validateCaptcha(request.getSession(true).getId(), captchaValue);//CaptchaUtil的validCaptcha方法檢驗驗證碼的正誤
if(isValid){
//doSomeThing,執行驗證碼通過的操作    
}else{
return "/login";//返回登錄頁面
}
...

驗證碼-Jcaptcha的使用