使用JCaptcha生成验证码

JCaptcha 官网地址 http://forge.octo.com/

引入Lib包 (包括一些依赖包commons-collections等)

从Servlet看起
<!-- 验证码Servlet -->
<servlet>
<servlet-name>jcaptcha</servlet-name>
<servlet-class>com.ighost.cms.common.checkcode.ImageCaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>jcaptcha</servlet-name>
<url-pattern>/CheckCode.svl</url-pattern>
</servlet-mapping>


package com.ighost.cms.common.checkcode;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
* 验证码生成Servlet
* @author ghost
*
*/
@SuppressWarnings("serial")
public class ImageCaptchaServlet extends HttpServlet {

//验证码生成类
private ImageCaptchaService imageCaptchaService;
//Spring中的配置名称
private String beanName = "imageCaptchaService";

/**
* 初始化ImageCaptchaService 对象
*/
@Override
public void init(ServletConfig config) throws ServletException {
   System.out.println("servlet init is in");
   super.init(config);
   WebApplicationContext context = WebApplicationContextUtils
            .getWebApplicationContext(config.getServletContext());
   imageCaptchaService = (ImageCaptchaService)context.getBean(beanName,ImageCaptchaService.class);
}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
   byte[] captchaChallengeAsJpeg = null;
   // the output stream to render the captcha image as jpeg into
   ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
   try {
    // get the session id that will identify the generated captcha.
    // the same id must be used to validate the response, the session id
    // is a good candidate!
    String captchaId = req.getSession().getId();
    // call the ImageCaptchaService getChallenge method
    BufferedImage challenge = imageCaptchaService
      .getImageChallengeForID(captchaId, req.getLocale());

    // a jpeg encoder
    JPEGImageEncoder jpegEncoder = JPEGCodec
      .createJPEGEncoder(jpegOutputStream);
    jpegEncoder.encode(challenge);
   } catch (IllegalArgumentException e) {
    resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    return;
   } catch (CaptchaServiceException e) {
    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    return;
   }

   captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

   // flush it in the response
   resp.setHeader("Cache-Control", "no-store");
   resp.setHeader("Pragma", "no-cache");
   resp.setDateHeader("Expires", 0);
   resp.setContentType("image/jpeg");
   ServletOutputStream responseOutputStream = resp.getOutputStream();
   responseOutputStream.write(captchaChallengeAsJpeg);
   responseOutputStream.flush();
   responseOutputStream.close();
}

}

Servlet中需要的类在Bean中的配置

<!-- 验证码生成器 -->
<bean id="fastHashMapCaptchaStore" class="com.octo.captcha.service.captchastore.FastHashMapCaptchaStore"/>
<bean id="captchaEngineEx" class="com.ighost.cms.common.checkcode.CaptchaEngineEx"/>
<bean id="imageCaptchaService" class="com.ighost.cms.common.checkcode.CaptchaService">
   <constructor-arg type="com.octo.captcha.service.captchastore.CaptchaStore" index="0">
    <ref bean="fastHashMapCaptchaStore"/>
   </constructor-arg>
   <constructor-arg type="com.octo.captcha.engine.CaptchaEngine" index="1">
    <ref bean="captchaEngineEx"/>
   </constructor-arg>
   <constructor-arg index="2">
    <value>180</value>   
   </constructor-arg>
   <constructor-arg index="3">
    <value>100000</value>   
   </constructor-arg>
   <constructor-arg index="4">
    <value>75000</value>   
   </constructor-arg> 
</bean>

具体完成生成的类
package com.ighost.cms.common.checkcode;

import com.octo.captcha.engine.CaptchaEngine;
import com.octo.captcha.service.captchastore.CaptchaStore;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;

/*
* 自定义的验证码生成器
*/
public class CaptchaService extends DefaultManageableImageCaptchaService {

public CaptchaService(){
   super();
}

/**
* @param minSeconds
* @param maxStoreSize 最大缓存大小
* @param loadBefore
*/
public CaptchaService(int minSeconds, int maxStoreSize, int loadBefore){
   super(minSeconds, maxStoreSize, loadBefore);
}

public CaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine, 
        int minSeconds, int maxStroreSize, int loadBefore){
   super(captchaStore, captchaEngine, minSeconds, maxStroreSize, loadBefore);
}

/**
* 重写验证方法 
* 掩盖异常 当出现异常时判定为验证失败
*/
@Override
public Boolean validateResponseForID(String ID, Object response) {
   Boolean isHuman;
  
   try{
    isHuman = super.validateResponseForID(ID, response);
   }
   catch(Exception e){
    isHuman = false;   
   }
  
   return isHuman;
}
}

package com.ighost.cms.common.checkcode;

import java.awt.Color;

import com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator;
import com.octo.captcha.component.image.backgroundgenerator.GradientBackgroundGenerator;
import com.octo.captcha.component.image.color.SingleColorGenerator;
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.BaffleTextDecorator;
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;

/**
* 自定义的验证码生成引擎
* @author ghost
*
*/
public class CaptchaEngineEx extends ListImageCaptchaEngine {

/**
* 生成验证码的具体方法
*/
@Override
protected void buildInitialFactories() {
  
   //验证码的最小长度
   Integer minAcceptedWordLength = new Integer(4);
   //验证码的最大长度
   Integer maxAcceptedWordLength = new Integer(5);
  
   //验证码图片的高度宽度设定
   Integer imageHeight = new Integer(40);
   Integer imageWidth = new Integer(100);
  
   //验证码中显示的字体大小
   Integer minFontSize = new Integer(20);
   Integer maxFontSize = new Integer(22);
  
   //随机字符生成
   //abcdefghijklmnopqrstuvwxyz
   WordGenerator wordGenerator = new RandomWordGenerator("0123456789");
  
   //背景颜色随机生成
   BackgroundGenerator backgroundGenerator = new GradientBackgroundGenerator(
     imageWidth, imageHeight, Color.white,Color.white); 

   //字体随机生成
   FontGenerator fontGenerator = new RandomFontGenerator(minFontSize, maxFontSize);
  
   //验证码的颜色
   SingleColorGenerator singleColor = new SingleColorGenerator(Color.blue);
  
   BaffleTextDecorator baffleTextDecorator = new BaffleTextDecorator(1, Color.white);
   //可以创建多个
   //LineTextDecorator lineTextDecorator = new LineTextDecorator(1, Color.blue);
   //TextDecorator[] textDecorator = new TextDecorator[2];
   //textDecorator[0] = lineTextDecorator;
   TextDecorator[] textDecorator = new TextDecorator[1];
   textDecorator[0] = baffleTextDecorator;
  
   TextPaster textPaster = new DecoratedRandomTextPaster(
     minAcceptedWordLength, maxAcceptedWordLength, singleColor,textDecorator);
   //生成图片输出
   WordToImage wordToImage = new ComposedWordToImage(
     fontGenerator, backgroundGenerator, textPaster);
  
   addFactory(new GimpyFactory(wordGenerator, wordToImage)); 
}

}


最后在jsp页面中只需使用如下调用即可
<img id="checkcode" alt="看不清,点击换一张" src="../CheckCode.svl" border="1px" onclick="this.src='../CheckCode.svl?date=' + new Date().getTime()">


你可能感兴趣的:(spring,cms,bean,Web,servlet)