验证码-Jcaptcha的使用

Posted popcorn丫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了验证码-Jcaptcha的使用相关的知识,希望对你有一定的参考价值。

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的使用的主要内容,如果未能解决你的问题,请参考以下文章

Spring中使用Jcaptcha实现校验码验证

验证码-Jcaptcha的使用

jcaptcha配置验证码

jcaptcha进阶

java后台验证码工具

本人初学Java,有啥好的图形验证码推荐吗?