MyException - 我的异常网
当前位置:我的异常网» 软件架构设计 » 运用 jcaptcha 产生图片校验码

运用 jcaptcha 产生图片校验码

www.MyException.Cn  网友分享于:2013-11-05  浏览:17次
使用 jcaptcha 产生图片校验码
具体使用的例子: www.tongriben.com

第一步:下载 jcaptcha-all-1.0-RC2.0.1.jar
第二步:代码实现
CaptchaServiceSingleton.java
 
package com.yh.web.jcaptcha;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator;
import com.octo.captcha.component.image.backgroundgenerator.GradientBackgroundGenerator;
import com.octo.captcha.component.image.fontgenerator.FontGenerator;
import com.octo.captcha.component.image.fontgenerator.RandomFontGenerator;
import com.octo.captcha.component.image.textpaster.RandomTextPaster;
import com.octo.captcha.component.image.textpaster.SimpleTextPaster;
import com.octo.captcha.component.image.textpaster.TextPaster;
import com.octo.captcha.component.image.wordtoimage.ComposedWordToImage;
import com.octo.captcha.component.image.wordtoimage.WordToImage;
import com.octo.captcha.component.wordgenerator.RandomWordGenerator;
import com.octo.captcha.component.wordgenerator.WordGenerator;
import com.octo.captcha.engine.image.ListImageCaptchaEngine;
import com.octo.captcha.image.ImageCaptcha;
import com.octo.captcha.image.ImageCaptchaFactory;
import com.octo.captcha.image.gimpy.GimpyFactory;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class CaptchaServiceSingleton extends ListImageCaptchaEngine {
	private static Logger log = Logger.getLogger(CaptchaServiceSingleton.class);

	private static final Integer MIN_WORD_LENGTH = new Integer(4);

	private static final Integer MAX_WORD_LENGTH = new Integer(6);

	private static final Integer IMAGE_WIDTH = new Integer(70);

	private static final Integer IMAGE_HEIGHT = new Integer(20);

	private static final Integer MIN_FONT_SIZE = new Integer(12);

	private static final Integer MAX_FONT_SIZE = new Integer(14);

	private static final String NUMERIC_CHARS = "23456789";// No numeric 0

	private static final String UPPER_ASCII_CHARS = "ABCDEFGHJKLMNPQRSTXYZ";// No

	// upper
	// O I

	// we dont use the lower characters because it cause dificult in some case,
	// so that
	// we must always UPPERCASE the input from user (currently in
	// OnlineUserImpl)
	private static final String LOWER_ASCII_CHARS = "abcdefghjkmnpqrstxyz";// No

	// lower
	// o i

	/**
	 * Singleton instance of this class
	 */
	private static CaptchaServiceSingleton instance = new CaptchaServiceSingleton();

	private ArrayList textPasterList;

	private ArrayList backgroundGeneratorList;

	private ArrayList fontGeneratorList;

	ImageCaptcha imageCaptcha = null;

	/**
	 * Private constructor to prevent instantiation
	 */
	private CaptchaServiceSingleton() {
	}

	public static CaptchaServiceSingleton getInstance() {
		return instance;
	}

	protected void buildInitialFactories() {
		try {
			textPasterList = new ArrayList();
			backgroundGeneratorList = new ArrayList();
			fontGeneratorList = new ArrayList();

			textPasterList.add(new SimpleTextPaster(MIN_WORD_LENGTH,
					MAX_WORD_LENGTH, Color.black));
			textPasterList.add(new RandomTextPaster(MIN_WORD_LENGTH,
					MAX_WORD_LENGTH, Color.black));
			textPasterList.add(new SimpleTextPaster(MIN_WORD_LENGTH,
					MAX_WORD_LENGTH, Color.black));
			textPasterList.add(new RandomTextPaster(MIN_WORD_LENGTH,
					MAX_WORD_LENGTH, Color.black));
			textPasterList.add(new SimpleTextPaster(MIN_WORD_LENGTH,
					MAX_WORD_LENGTH, Color.blue));
			textPasterList.add(new RandomTextPaster(MIN_WORD_LENGTH,
					MAX_WORD_LENGTH, Color.blue));

			backgroundGeneratorList.add(new GradientBackgroundGenerator(
					IMAGE_WIDTH, IMAGE_HEIGHT, Color.orange, Color.white));
			backgroundGeneratorList.add(new GradientBackgroundGenerator(
					IMAGE_WIDTH, IMAGE_HEIGHT, Color.white, Color.green));
			backgroundGeneratorList.add(new GradientBackgroundGenerator(
					IMAGE_WIDTH, IMAGE_HEIGHT, Color.gray, Color.white));
			backgroundGeneratorList.add(new GradientBackgroundGenerator(
					IMAGE_WIDTH, IMAGE_HEIGHT, Color.white, Color.orange));
			backgroundGeneratorList.add(new GradientBackgroundGenerator(
					IMAGE_WIDTH, IMAGE_HEIGHT, Color.green, Color.white));
			backgroundGeneratorList.add(new GradientBackgroundGenerator(
					IMAGE_WIDTH, IMAGE_HEIGHT, Color.yellow, Color.white));
			backgroundGeneratorList.add(new GradientBackgroundGenerator(
					IMAGE_WIDTH, IMAGE_HEIGHT, Color.white, Color.magenta));

			

			// fontGeneratorList.add(new
			// TwistedAndShearedRandomFontGenerator(MIN_FONT_SIZE,
			// MAX_FONT_SIZE));
			// fontGeneratorList.add(new
			// TwistedRandomFontGenerator(MIN_FONT_SIZE, MAX_FONT_SIZE));// link
			// character too much
			fontGeneratorList.add(new RandomFontGenerator(MIN_FONT_SIZE,
					MAX_FONT_SIZE));// to easy to read
			// fontGeneratorList.add(new
			// DeformedRandomFontGenerator(MIN_FONT_SIZE, MAX_FONT_SIZE));// to
			// small font

			// no char upper O, char lower o and numerric 0 because user cannot
			// answer
			WordGenerator words = new RandomWordGenerator(NUMERIC_CHARS
					+ UPPER_ASCII_CHARS);

			for (Iterator fontIter = fontGeneratorList.iterator(); fontIter
					.hasNext();) {
				FontGenerator font = (FontGenerator) fontIter.next();
				for (Iterator backIter = backgroundGeneratorList.iterator(); backIter
						.hasNext();) {
					BackgroundGenerator back = (BackgroundGenerator) backIter
							.next();
					for (Iterator textIter = textPasterList.iterator(); textIter
							.hasNext();) {
						TextPaster parser = (TextPaster) textIter.next();

						WordToImage word2image = new ComposedWordToImage(font,
								back, parser);
						ImageCaptchaFactory factory = new GimpyFactory(words,
								word2image);
						addFactory(factory);
					}
				}
			}
		} catch (Exception ex) {
			log.error("产生校验码初始化异常 == " + ex);
			// throw ex;
		}
	}

	/**
	 * Write the captcha image of current user to the servlet response
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 * @throws IOException
	 */
	public void writeCaptchaImage(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		imageCaptcha = getNextImageCaptcha();
		HttpSession session = request.getSession();
		session.setAttribute("imageCaptcha", imageCaptcha);
		BufferedImage image = (BufferedImage) imageCaptcha.getChallenge();

		OutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
			// render the captcha challenge as a JPEG image in the response
			response.setHeader("Cache-Control", "no-store");
			response.setHeader("Pragma", "no-cache");
			response.setDateHeader("Expires", 0);

			response.setContentType("image/jpeg");

			JPEGImageEncoder encoder = JPEGCodec
					.createJPEGEncoder(outputStream);
			encoder.encode(image);

			outputStream.flush();
			outputStream.close();
			outputStream = null;// no close twice
		} catch (IOException ex) {
			log.error("产生图片异常 == " + ex);
			throw ex;
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException ex) {
				}
			}
			imageCaptcha.disposeChallenge();
		}
	}

	public boolean validateCaptchaResponse(String validateCode,
			HttpSession session) {
		boolean flag = true;
		try {
			imageCaptcha = (ImageCaptcha) session.getAttribute("imageCaptcha");
			if (imageCaptcha == null) {
				// log.info("validateCaptchaResponse returned false due to
				// imageCaptcha is null");
				flag = false;
			}
			//validateCode = validateCode.toLowerCase();// use upper case for
			validateCode = validateCode.toUpperCase();// use upper case for
			// easier usage
flag = (imageCaptcha.validateResponse(validateCode)).booleanValue();
			session.removeAttribute("imageCaptcha");
			return flag;
		} catch (Exception ex) {
			ex.printStackTrace();
			log.error("校验码校验异常 == " + ex);
			return false;
		}
	}
	
}


ImageCaptchaServlet.java
 
package com.yh.web.servlet;

import java.io.IOException;

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

import com.yh.web.jcaptcha.CaptchaServiceSingleton;
import com.octo.captcha.service.CaptchaServiceException;

public class ImageCaptchaServlet extends HttpServlet {

	private static final long serialVersionUID = -5382766069139170499L;
	public void init(ServletConfig servletConfig) throws ServletException {

		super.init(servletConfig);

	}

	protected void doGet(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse) throws ServletException,
			IOException {
		System.out.println("---------- ImageCaptchaServlet pass here -------------");
		try {
			CaptchaServiceSingleton.getInstance().writeCaptchaImage(
					httpServletRequest, httpServletResponse);

		} catch (IllegalArgumentException e) {
			httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		} catch (CaptchaServiceException e) {
			httpServletResponse
					.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return;
		}
	}
}

jsp页面增加校验码内容:
<tr><td>
校验码:<input type="text" size="8" name="checkCode" id="checkCode" class="normal_input"/><img src="/jcaptcha" id="checkCodeImg" onclick="this.src='/jcaptcha?now=' + new Date().getTime()" alt="看不清,点击换一张" >请输入校验码,大小写不区分<br> 如看不清,请点击图片换一张
</tr></td>


判断校验码是否正确的java代码:
		HttpSession session = request.getSession();
		boolean isResponseCorrect = false;
		// retrieve the response
		String validateCode = checkCode.trim();
		System.out.println("checkCode == "
				+ checkCode);
		try {
			isResponseCorrect = CaptchaServiceSingleton.getInstance()
					.validateCaptchaResponse(validateCode, session);

			return isResponseCorrect;
		} catch (Exception e) {
			// should not happen, may be thrown if the id is not valid

			return false;
		}
1 楼 liusu 2011-09-26  
checkCode在哪里啊???

文章评论

不懂技术不要对懂技术的人说这很容易实现
不懂技术不要对懂技术的人说这很容易实现
程序员都该阅读的书
程序员都该阅读的书
为什么程序员都是夜猫子
为什么程序员都是夜猫子
如何区分一个程序员是“老手“还是“新手“?
如何区分一个程序员是“老手“还是“新手“?
程序猿的崛起——Growth Hacker
程序猿的崛起——Growth Hacker
亲爱的项目经理,我恨你
亲爱的项目经理,我恨你
“肮脏的”IT工作排行榜
“肮脏的”IT工作排行榜
中美印日四国程序员比较
中美印日四国程序员比较
程序员周末都喜欢做什么?
程序员周末都喜欢做什么?
程序员和编码员之间的区别
程序员和编码员之间的区别
老美怎么看待阿里赴美上市
老美怎么看待阿里赴美上市
Java程序员必看电影
Java程序员必看电影
我的丈夫是个程序员
我的丈夫是个程序员
程序员必看的十大电影
程序员必看的十大电影
旅行,写作,编程
旅行,写作,编程
老程序员的下场
老程序员的下场
漫画:程序员的工作
漫画:程序员的工作
为啥Android手机总会越用越慢?
为啥Android手机总会越用越慢?
Web开发人员为什么越来越懒了?
Web开发人员为什么越来越懒了?
要嫁就嫁程序猿—钱多话少死的早
要嫁就嫁程序猿—钱多话少死的早
一个程序员的时间管理
一个程序员的时间管理
60个开发者不容错过的免费资源库
60个开发者不容错过的免费资源库
写给自己也写给你 自己到底该何去何从
写给自己也写给你 自己到底该何去何从
我跳槽是因为他们的显示器更大
我跳槽是因为他们的显示器更大
鲜为人知的编程真相
鲜为人知的编程真相
10个调试和排错的小建议
10个调试和排错的小建议
科技史上最臭名昭著的13大罪犯
科技史上最臭名昭著的13大罪犯
代码女神横空出世
代码女神横空出世
程序员应该关注的一些事儿
程序员应该关注的一些事儿
程序员最害怕的5件事 你中招了吗?
程序员最害怕的5件事 你中招了吗?
当下全球最炙手可热的八位少年创业者
当下全球最炙手可热的八位少年创业者
聊聊HTTPS和SSL/TLS协议
聊聊HTTPS和SSL/TLS协议
团队中“技术大拿”并非越多越好
团队中“技术大拿”并非越多越好
做程序猿的老婆应该注意的一些事情
做程序猿的老婆应该注意的一些事情
Java 与 .NET 的平台发展之争
Java 与 .NET 的平台发展之争
如何成为一名黑客
如何成为一名黑客
“懒”出效率是程序员的美德
“懒”出效率是程序员的美德
十大编程算法助程序员走上高手之路
十大编程算法助程序员走上高手之路
10个帮程序员减压放松的网站
10个帮程序员减压放松的网站
Web开发者需具备的8个好习惯
Web开发者需具备的8个好习惯
初级 vs 高级开发者 哪个性价比更高?
初级 vs 高级开发者 哪个性价比更高?
那些争议最大的编程观点
那些争议最大的编程观点
什么才是优秀的用户界面设计
什么才是优秀的用户界面设计
我是如何打败拖延症的
我是如何打败拖延症的
程序员眼里IE浏览器是什么样的
程序员眼里IE浏览器是什么样的
软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有