java验证码组件kaptcha使用方法

时间:2022-10-27 20:37:09

使用方法

项目中导入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.启动服务,运行程序效果如下:

java验证码组件kaptcha使用方法

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使用方法