使用方法

项目中导入kaptcha-2.3.jar包

在web.xml里面新增

<!-- 登陆验证码Kaptcha -->
    <servlet>
        <servlet-name>Kaptcha</servlet-name>
        <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
                   <init-param>
            <param-name>kaptcha.producer.impl</param-name>
            <param-value>com.google.code.kaptcha.impl.DefaultKaptcha </param-value>
        </init-param>
                   <init-param>
                            <param-name>kaptcha.textproducer.font.color</param-name>
                            <param-value>black</param-value>
                   </init-param>
                   <init-param>
                            <param-name>kaptcha.textproducer.char.space</param-name>
                            <param-value>10</param-value>
                   </init-param>
                   <init-param>
                            <param-name>kaptcha.border</param-name>
                            <param-value>no</param-value>
                   </init-param>
                   <init-param>
                            <param-name>kaptcha.border.thickness</param-name>
                            <param-value>0</param-value>
                   </init-param>
                   <init-param>
                            <param-name>kaptcha.textproducer.font.size</param-name>
                            <param-value>35</param-value>
                   </init-param>
                   <init-param>
                            <param-name>kaptcha.textproducer.char.length</param-name>
                            <param-value>4</param-value>
                   </init-param>
                   <init-param>
            <param-name>kaptcha.image.width</param-name>
            <param-value>150</param-value>
        </init-param>
        <init-param>
            <param-name>kaptcha.image.height</param-name>
            <param-value>50</param-value>
        </init-param>
        <init-param>
                            <param-name>kaptcha.background.clear.from</param-name>
                            <param-value>255,255,255</param-value>
                   </init-param>
                   <init-param>
                            <param-name>kaptcha.background.clear.to</param-name>
                            <param-value>255,255,255</param-value>
                   </init-param>
                   <init-param>
            <param-name>kaptcha.textproducer.char.string</param-name>
            <param-value>0123456789</param-value>
        </init-param>
        <init-param>
            <param-name>kaptcha.textproducer.font.names</param-name>
            <param-value>Arial Black</param-value>
        </init-param>
         <init-param>
            <param-name>kaptcha.noise.impl</param-name>
            <param-value>com.google.code.kaptcha.impl.NoNoise</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>Kaptcha</servlet-name>
        <url-pattern>/kaptcha.jpg</url-pattern>
</servlet-mapping>

在页面上新增

<img id="img" src="kaptcha.jpg" width="90" height="25" onclick="refresh();" alt="点击更换验证码"/>
function refresh() {
                  document.getElementById('img').src="kaptcha.jpg?"+Math.random();
}

在action里获取验证码ID:

request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);

Jcaptcha验证码生成组件用法

1.创建项目JcaptchaDemo

2.引入相关.jar文件

jcaptcha-1.0-all.jar;

commons-logging-1.0.4.jar;

commons-collections-2.1.1.jar

3.创建GMailEngine,仿照JCaptcha2.0编写GMail验证码样式的图片引擎.,具体的代码如下:

设置生成验证的样式就是在这里设置。

package com.zsw.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.image.ImageFilter;
import com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator;
import com.octo.captcha.component.image.backgroundgenerator.UniColorBackgroundGenerator;
import com.octo.captcha.component.image.color.RandomListColorGenerator;
import com.octo.captcha.component.image.deformation.ImageDeformation;
import com.octo.captcha.component.image.deformation.ImageDeformationByFilters;
import com.octo.captcha.component.image.fontgenerator.FontGenerator;
import com.octo.captcha.component.image.fontgenerator.RandomFontGenerator;
import com.octo.captcha.component.image.textpaster.DecoratedRandomTextPaster;
import com.octo.captcha.component.image.textpaster.TextPaster;
import com.octo.captcha.component.image.textpaster.textdecorator.TextDecorator;
import com.octo.captcha.component.image.wordtoimage.DeformedComposedWordToImage;
import com.octo.captcha.component.image.wordtoimage.WordToImage;
import com.octo.captcha.component.word.FileDictionary;
import com.octo.captcha.component.word.wordgenerator.ComposeDictionaryWordGenerator;
import com.octo.captcha.component.word.wordgenerator.WordGenerator;
import com.octo.captcha.engine.image.ListImageCaptchaEngine;
import com.octo.captcha.image.gimpy.GimpyFactory;
/**
 * 仿照JCaptcha2.0编写GMail验证码样式的图片引擎.  
 * @author Administrator
 */
public class GMailEngine extends ListImageCaptchaEngine  {
 @Override
 protected void buildInitialFactories() {
  
   int minWordLength = 4;
   int maxWordLength = 5;
   int fontSize = 24;
   int imageWidth = 100;
   int imageHeight = 40;
           
   //word generator
   WordGenerator dictionnaryWords = new ComposeDictionaryWordGenerator(new FileDictionary("toddlist"));
           
   //word2image components 
   TextPaster randomPaster = new DecoratedRandomTextPaster(
           minWordLength, 
           maxWordLength,
           new RandomListColorGenerator(new Color[] { 
             new Color(23, 170, 27), 
             new Color(220, 34, 11),   
             new Color(23, 67, 172) 
           }), 
                            new TextDecorator[] {}
         );
           
   BackgroundGenerator background = new UniColorBackgroundGenerator(imageWidth, imageHeight, Color.white);
   FontGenerator font = new RandomFontGenerator(
        fontSize, 
        fontSize, 
        new Font[] {
                    new Font("nyala", Font.BOLD, fontSize), 
                    new Font("Bell MT", Font.PLAIN, fontSize),   
                    new Font("Credit valley", Font.BOLD, fontSize) 
                   });
   ImageDeformation postDef = new ImageDeformationByFilters(new ImageFilter[] {});
   ImageDeformation backDef = new ImageDeformationByFilters(new ImageFilter[] {});
   ImageDeformation textDef = new ImageDeformationByFilters(new ImageFilter[] {}); 
   WordToImage word2image = new DeformedComposedWordToImage(font, background, randomPaster, backDef, textDef,postDef);   
   addFactory(new GimpyFactory(dictionnaryWords, word2image));
 }
}

4.在这里创建一个单例类:

package com.zsw.servlet;
import com.octo.captcha.service.captchastore.FastHashMapCaptchaStore;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;
import com.octo.captcha.service.image.ImageCaptchaService;
public class CaptchaServiceSingleton {
 
 private static ImageCaptchaService instance = new DefaultManageableImageCaptchaService(new FastHashMapCaptchaStore(), new GMailEngine(), 180, 100000,75000);
 public static ImageCaptchaService getInstance() {
  return instance;
 }
}

5.创建ImageCaptchaServlet.java,它是一个Servlet

图片src,制定这个Servlet在Web.xml中配置的名称,获取验证码图片。具体的内容如下:

package com.zsw.servlet;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.octo.captcha.service.CaptchaServiceException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class ImageCaptchaServlet extends HttpServlet {
 
 private static final long serialVersionUID = 1L;
    public ImageCaptchaServlet() {
    }
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
  byte[] captchaChallengeAsJpeg = null;
  ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
  
  try {
    String captchaId = request.getSession().getId();   
    BufferedImage challenge = CaptchaServiceSingleton.getInstance().getImageChallengeForID(captchaId,request.getLocale());
   JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
   jpegEncoder.encode(challenge);
  } catch (IllegalArgumentException e) {
   response.sendError(HttpServletResponse.SC_NOT_FOUND);
   return;
  } catch (CaptchaServiceException e) {
   response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
   return;
  }
  captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
  // flush it in the response
  response.setHeader("Cache-Control", "no-store");
  response.setHeader("Pragma", "no-cache");
  response.setDateHeader("Expires", 0);
  response.setContentType("image/jpeg");
  ServletOutputStream responseOutputStream = response.getOutputStream();
  responseOutputStream.write(captchaChallengeAsJpeg);
  
  responseOutputStream.flush();
  responseOutputStream.close();
 }
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
 }
}

6.创建index.jsp以及sample.jsp

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="sample.jsp">
 <table style="width:300px; height:30px;" cellpadding="1" cellspacing="1" border="1">
  <tr>
   <td align="right">
    <input type='text' name='j_captcha_response' value=''>
   </td>
   <td align="left">
    <img src="ImageCaptchaServlet">
   </td>
  </tr>
 </table>
</form>
</body>
</html>

sample.jsp:处理检验验证码

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="UTF-8"%>
<%@page import="com.octo.captcha.service.CaptchaServiceException"%>
<%@page import="com.zsw.servlet.CaptchaServiceSingleton"%>
<%
 Boolean isResponseCorrect = Boolean.FALSE;
 String captchaId = request.getSession().getId();
 String responsestr = request.getParameter("j_captcha_response");
 
 try {
  isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(captchaId, responsestr);
  if(isResponseCorrect){
  }else{
   out.print("It's worng......");
  }
 } catch (CaptchaServiceException e) {
 }
%>

7.启动服务,运行程序效果如下:

8, 对设置验证样式的引擎类,进行重构,及支持验证码有背景图片

8.1 创建com.zsw.captcha包,将相关背景图片放入该包中;

8.2 创建JCaptchaEngine.java,具体内容如下:

package com.zsw.common;
import java.awt.Color;
import java.awt.Font;
import com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator;
import com.octo.captcha.component.image.backgroundgenerator.FileReaderRandomBackgroundGenerator;
import com.octo.captcha.component.image.color.RandomListColorGenerator;
import com.octo.captcha.component.image.fontgenerator.FontGenerator;
import com.octo.captcha.component.image.fontgenerator.RandomFontGenerator;
import com.octo.captcha.component.image.textpaster.DecoratedRandomTextPaster;
import com.octo.captcha.component.image.textpaster.TextPaster;
import com.octo.captcha.component.image.textpaster.textdecorator.TextDecorator;
import com.octo.captcha.component.image.wordtoimage.ComposedWordToImage;
import com.octo.captcha.component.image.wordtoimage.WordToImage;
import com.octo.captcha.component.word.wordgenerator.RandomWordGenerator;
import com.octo.captcha.component.word.wordgenerator.WordGenerator;
import com.octo.captcha.engine.image.ListImageCaptchaEngine;
import com.octo.captcha.image.gimpy.GimpyFactory;
/**
 * 生成验证码图片
 */
public class JCaptchaEngine extends ListImageCaptchaEngine {
 public static final String IMAGE_CAPTCHA_KEY = "imageCaptcha";// ImageCaptcha对象存放在Session中的key
 public static final String CAPTCHA_INPUT_NAME = "j_captcha";// 验证码输入表单名称
 public static final String CAPTCHA_IMAGE_URL = "/captcha.jpg";// 验证码图片URL
 private static final Integer MIN_WORD_LENGTH = 4;// 验证码最小长度
 private static final Integer MAX_WORD_LENGTH = 4;// 验证码最大长度
 private static final Integer IMAGE_HEIGHT = 28;// 验证码图片高度
 private static final Integer IMAGE_WIDTH = 80;// 验证码图片宽度
 private static final Integer MIN_FONT_SIZE = 16;// 验证码最小字体
 private static final Integer MAX_FONT_SIZE = 16;// 验证码最大字体
 private static final String RANDOM_WORD = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";// 随机字符
 private static final String IMAGE_PATH = "./com/zsw/captcha/";// 随机背景图片路径
 
 // 验证码随机字体
 private static final Font[] RANDOM_FONT = new Font[] { 
   new Font("nyala", Font.BOLD, MIN_FONT_SIZE), 
   new Font("Arial", Font.BOLD, MIN_FONT_SIZE),
   new Font("Bell MT", Font.BOLD, MIN_FONT_SIZE), 
   new Font("Credit valley", Font.BOLD, MIN_FONT_SIZE),
   new Font("Impact", Font.BOLD, MIN_FONT_SIZE) 
 };
 // 验证码随机颜色
 private static final Color[] RANDOM_COLOR = new Color[] { 
   new Color(255, 255, 255), 
   new Color(255, 220, 220), 
   new Color(220, 255, 255), 
   new Color(220, 220, 255),
   new Color(255, 255, 220), 
   new Color(220, 255, 220) 
 };
 // 生成验证码
 @Override
 protected void buildInitialFactories() {
  
  RandomListColorGenerator randomListColorGenerator = new RandomListColorGenerator(RANDOM_COLOR);// 验证码随机颜色
  BackgroundGenerator backgroundGenerator = new FileReaderRandomBackgroundGenerator(IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_PATH); //验证码背景图片
  WordGenerator wordGenerator = new RandomWordGenerator(RANDOM_WORD);
  FontGenerator fontGenerator = new RandomFontGenerator(MIN_FONT_SIZE, MAX_FONT_SIZE, RANDOM_FONT);// 验证码随机字体
  TextDecorator[] textDecorator = new TextDecorator[] {};
  TextPaster textPaster = new DecoratedRandomTextPaster(MIN_WORD_LENGTH, MAX_WORD_LENGTH, randomListColorGenerator, textDecorator);
  WordToImage wordToImage = new ComposedWordToImage(fontGenerator, backgroundGenerator, textPaster);
  addFactory(new GimpyFactory(wordGenerator, wordToImage));
 }
}

8.3 修改第4步中的单例类,具体内容如下:

package com.zsw.servlet;
import com.octo.captcha.service.captchastore.FastHashMapCaptchaStore;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.zsw.common.JCaptchaEngine;
public class CaptchaServiceSingleton {
 private static ImageCaptchaService instance = new DefaultManageableImageCaptchaService(new FastHashMapCaptchaStore(), new JCaptchaEngine(), 180, 100000,75000);
 public static ImageCaptchaService getInstance() {
  return instance;
 }
}

8.4 运行启动,效果图如下:

java验证码组件kaptcha使用方法的更多相关文章

  1. 推荐一款java的验证码组件——kaptcha

    使用方法: 项目中导入kaptcha-2.3.jar包 在web.xml里面新增:   <!-- 登陆验证码Kaptcha --> <servlet> <servlet- ...

  2. 在 Java EE 组件中使用 Camel Routes

    摘要:你可以通过集成 Camel 和 WildFly 应用服务器(使用 WildFly-Camel 子系统)在 Java EE 组件中开始使用 Apache Camel Routes. [编者按]作者 ...

  3. kaptcha 验证码组件使用

    kaptcha 验证码组件使用简介   kaptcha 是一个非常实用的验证码生成工具.有了它,你可以生成各种样式的验证码,因为它是可配置的.kaptcha工作的原理是调用 com.google.co ...

  4. kaptcha图形验证码组件

    kaptcha 是一个非常实用的验证码生成工具.有了它,你可以生成各种样式的验证码,因为它是可配置的.kaptcha工作的原理是调用 com.google.code.kaptcha.servlet.K ...

  5. kaptcha Java验证码

    原文:http://www.cnblogs.com/chizizhixin/p/5311619.html 在项目中经常会使用验证码,kaptcha 就一个非常不错的开源框架,分享下自己在项目中的使用: ...

  6. java 调用webservice的各种方法总结

    java 调用webservice的各种方法总结 几种流行的开源WebService框架Axis1,Axis2,Xfire,CXF,JWS比较 方法一:创建基于JAX-WS的webservice(包括 ...

  7. Java Swing 绝对布局管理方法,null布局(转)

    首先把相关容器的布局方式设为 setLayout(null); 然后调用组件的  setBounds() 方法 设置button的位置为(100,100) 长宽分别为 60,25 jButton.se ...

  8. springMVC+Java验证码完善注册功能

    这篇文章简单的写了一个java验证码,为之前写过的springMVC注册功能加上验证码,验证码的作用就不多说了,防止机器人程序恶意注册什么的.. 其中User.java,加上了password和cod ...

  9. java制作验证码(java验证码小程序)

    手动制作java的验证码 Web应用验证码的组成: (1)输入框 (2)显示验证码的图片 验证码的制作流程: 生成验证码的容器使用 j2ee的servlet 生成图片需要的类: (1) Buffere ...

随机推荐

  1. DirectShowNet 使用摄像头录像+录音

    http://www.cnblogs.com/endv/p/6052511.html // ------------------------------------------------------ ...

  2. Json字符串反序列化

    using DevComponents.DotNetBar; using MyControl; using Newtonsoft.Json; using System; using System.Co ...

  3. “Win10 UAP 开发系列”之主题模式切换

    微软动作真是快,本来想写WP8.1RT系列,结果刚整理了一点就出Win10 UAP了.不过还好RT到Win10的差别还不算太大.前两天参加了Win10开发极客秀,虽然没获奖,不过在韦恩卑鄙的帮助下顺利 ...

  4. 使用ASP.NET MVC局部视图避免JS拼接HTML,编写易于维护的HTML页面

    以前使用ASP.NET WebForm开发时,喜欢使用Repeater控件嵌套的方式开发前台页面,这样就不用JS拼接HTML或者后台拼接HTML了,写出的HTML页面美观.简捷.易于维护,由于不用JS ...

  5. .NET Core 单元测试 MSTest

    .NET Core 单元测试 MSTest ,MSTest Framework 已经支持 .NET Core RC2 / ASP.NET Core RC2. 之前都是使用 xUnit.net ,现在 ...

  6. svn无法创建分支的解决方法

    创建分支时出现错误 Access to '/svn/project01/!svn/rvr/18022/trunk' forbidden 解决方法: 找到project01仓库的根目录,假如在d:\sv ...

  7. 【C#】添加引用方式抛出和捕获干净的WebService异常

    说明:[干净]指的是客户端在捕获WebService(下称WS)抛出的异常时,得到的ex.Message就是WS方法中抛出的异常消息,不含任何“杂质”. 前提:你对WS有编写权.就是说如果你调的是别人 ...

  8. matlab 调用dos命令和文件操作

    第一.利用!直接调用,简单方便,可以带操作对象:!del A.bat 第二.调用system函数或者dos函数,既可以实现功能,又返回参数,能检查执行情况,方便后面程序的开发,推荐这个 [status ...

  9. 15天玩转redis —— 第六篇 有序集合类型

    今天我们说一下Redis中最后一个数据类型 “有序集合类型”,回首之前学过的几个数据结构,不知道你会不会由衷感叹,开源的世界真好,写这 些代码的好心人真的要一生平安哈,不管我们想没想的到的东西,在这个 ...

  10. Net重温之路一

    简述: 最简单的 Hello World 准备: 工具:VS2013 + SqlServer 2008 R2 我们将以.NET Framework 4.5 为基准 开始: 一:新建解决方案 > ...