1、从jcaptcha官方网站下载jcaptcha的发行包,并将其发行包中的jar文件考贝到本地项目WEB-INF目录下的lib目录中。
官方网址http://jcaptcha.sourceforge.net/
2、在web.xml文件中配置
- <servlet>
- <servlet-name>jcaptcha</servlet-name>
- <servlet-class>cn.hxex.order.core.jcaptcha.ImageCaptchaServlet</servlet-class>
- <load-on-startup>3</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>jcaptcha</servlet-name>
- <url-pattern>/captcha.jpg</url-pattern>
- </servlet-mapping>
3、jcaptcha在spring中的配置
- <bean id="channelProcessingFilter"
- class="org.acegisecurity.securechannel.ChannelProcessingFilter">
- <property name="channelDecisionManager">
- <ref local="channelDecisionManager"/>
- </property>
- <property name="filterInvocationDefinitionSource">
- <value>
- CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
- PATTERN_TYPE_APACHE_ANT
- /j_security_check=REQUIRES_CAPTCHA_ONCE_ABOVE_THRESOLD_REQUESTS
- </value>
- </property>
- </bean>
- <bean id="channelDecisionManager"
- class="org.acegisecurity.securechannel.ChannelDecisionManagerImpl">
- <property name="channelProcessors">
- <list>
- <ref local="testOnceAfterMaxRequestsCaptchaChannelProcessor"/>
- <ref local="alwaysTestAfterTimeInMillisCaptchaChannelProcessor"/>
- <ref local="alwaysTestAfterMaxRequestsCaptchaChannelProcessor"/>
- <ref local="alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor"/>
- </list>
- </property>
- </bean>
- <!-- REQUIRES_CAPTCHA_ONCE_ABOVE_THRESOLD_REQUESTS -->
- <bean id="testOnceAfterMaxRequestsCaptchaChannelProcessor"
- class="org.acegisecurity.captcha.TestOnceAfterMaxRequestsCaptchaChannelProcessor">
- <property name="thresold">
- <value>0</value>
- </property>
- <property name="entryPoint">
- <ref bean="captchaEntryPoint"/>
- </property>
- </bean>
- <!-- REQUIRES_CAPTCHA_ABOVE_THRESOLD_REQUESTS -->
- <bean id="alwaysTestAfterMaxRequestsCaptchaChannelProcessor"
- class="org.acegisecurity.captcha.AlwaysTestAfterMaxRequestsCaptchaChannelProcessor">
- <property name="thresold">
- <value>5</value>
- </property>
- <property name="entryPoint">
- <ref bean="captchaEntryPoint"/>
- </property>
- </bean>
- <!-- REQUIRES_CAPTCHA_AFTER_THRESOLD_IN_MILLIS -->
- <bean id="alwaysTestAfterTimeInMillisCaptchaChannelProcessor"
- class="org.acegisecurity.captcha.AlwaysTestAfterTimeInMillisCaptchaChannelProcessor">
- <property name="thresold">
- <value>5000</value>
- </property>
- <property name="entryPoint">
- <ref bean="captchaEntryPoint"/>
- </property>
- </bean>
- <!-- REQUIRES_CAPTCHA_BELOW_AVERAGE_TIME_IN_MILLIS_REQUESTS -->
- <bean
- id="alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor"
- class="org.acegisecurity.captcha.AlwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor">
- <property name="thresold">
- <value>20000</value>
- </property>
- <property name="entryPoint">
- <ref bean="captchaEntryPoint"/>
- </property>
- </bean>
- <bean id="captchaEntryPoint"
- class="org.acegisecurity.captcha.CaptchaEntryPoint">
- <!--验证码验证失败后转向的页面!-->
- <property name="captchaFormUrl">
- <value>/admin/login.jsp?login_error=code_error</value>
- </property>
- <property name="includeOriginalRequest">
- <value>false</value>
- </property>
- <property name="includeOriginalParameters">
- <value>false</value>
- </property>
- </bean>
- <bean id="captchaValidationProcessingFilter"
- class="org.acegisecurity.captcha.CaptchaValidationProcessingFilter">
- <property name="captchaService">
- <ref bean="captchaService"/>
- </property>
- <property name="captchaValidationParameter" value="j_captcha_response"/>
- </bean>
- <!-- imageCaptchaService is injected into captchaImageCreateController as well as to captchaService beans -->
- <!--自己定义的实体类(注意路径!!)-->
- <bean id="captchaService" class="cn.hxex.order.core.jcaptcha.JCaptchaServiceProxyImpl">
- <property name="jcaptchaService" ref="imageCaptchaService"/>
- </bean>
- <bean id="imageCaptchaService" class="com.octo.captcha.service.image.DefaultManageableImageCaptchaService">
- <constructor-arg type="com.octo.captcha.service.captchastore.CaptchaStore" index="0">
- <ref bean="fastHashMapCaptchaStore"/>
- </constructor-arg>
- <!-- (1) which captcha Engine you use -->
- <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>
- <bean id="fastHashMapCaptchaStore" class="com.octo.captcha.service.captchastore.FastHashMapCaptchaStore"/>
- <!-- (2) you can define more than one captcha engine here -->
- <bean id="captchaEngineEx"
- class="cn.hxex.order.core.jcaptcha.engine.CaptchaEngineEx">
- </bean>
- <bean id="filterChainProxy"
- class="org.acegisecurity.util.FilterChainProxy">
- <property name="filterInvocationDefinitionSource">
- <value>
- CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
- PATTERN_TYPE_APACHE_ANT
- /**=httpSessionContextIntegrationFilter,captchaValidationProcessingFilter,channelProcessingFilter,authenticationProcessingFilter,exceptionTranslationFilter,filterInvocationInterceptor
- </value>
- </property>
- </bean>
- <bean id="httpSessionContextIntegrationFilter"
- class="org.acegisecurity.context.HttpSessionContextIntegrationFilter">
- <!-- 将下面的property注释掉,验证码将无效!!! -->
- <property name="context">
- <value>
- org.acegisecurity.captcha.CaptchaSecurityContextImpl
- </value>
- </property>
- </bean>
- ·············省略了一些spring安全框架的bean,自己加去吧
4、编写jcaptcha的实体类
实体类包的路径一定要和spring配置文件里的路径一样
(1)CaptchaEngine 类
- package cn.hxex.order.core.jcaptcha.engine;
- import java.awt.Color;
- import com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator;
- import com.octo.captcha.component.image.backgroundgenerator
- .FunkyBackgroundGenerator;
- import com.octo.captcha.component.image.fontgenerator.FontGenerator;
- import com.octo.captcha.component.image.fontgenerator
- .TwistedAndShearedRandomFontGenerator;
- import com.octo.captcha.component.image.textpaster.RandomTextPaster;
- 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.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;
- /**
- * SpringSide Custom的认证图片
- *
- * @author cac
- */
- public class CaptchaEngine extends ListImageCaptchaEngine {
- /**
- * @see ListImageCaptchaEngine
- */
- protected void buildInitialFactories() {
- WordGenerator wordGenerator
- = new RandomWordGenerator("023456789");
- // nteger minAcceptedWordLength, Integer maxAcceptedWordLength,Color[]
- // textColors
- TextPaster textPaster = new RandomTextPaster(4,5, Color.WHITE);
- // Integer width, Integer height
- BackgroundGenerator backgroundGenerator
- = new FunkyBackgroundGenerator(100,40);
- // Integer minFontSize, Integer maxFontSize
- FontGenerator fontGenerator = new TwistedAndShearedRandomFontGenerator(20, 22);
- WordToImage wordToImage = new ComposedWordToImage(fontGenerator,
- backgroundGenerator, textPaster);
- addFactory(new GimpyFactory(wordGenerator, wordToImage));
- }
- }
(2)CaptchaEngineEx 类
- package cn.hxex.order.core.jcaptcha.engine;
- 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
- .LineTextDecorator;
- 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;
- /**
- * Captcha增强版本
- *
- * @author david.turing@gmail.com
- * @modifyTime 21:01:52
- * @description
- * <pre>
- * 安装 Captcha Instruction <br>
- * 1.add captchaValidationProcessingFilter
- * to applicationContext-acegi-security.xml<br>
- * 2.modify applicationContext-captcha-security.xml
- * <ul>
- * <li> make sure that captchaValidationProcessingFilter Call captchaService
- <li> config CaptchaEngine for captchaService (refer imageCaptchaService)
- <li> write your own CaptchaEngine
- <li> config the following, so that We use CaptchaEngineEx to generate the
- captcha image.
- </ul>
- <constructor-arg
- * type="com.octo.captcha.engine.CaptchaEngine" index="1">
- * <ref bean="captchaEngineEx"/gt; </constructor-arg>
- * </pre>
- */
- public class CaptchaEngineEx extends ListImageCaptchaEngine {
- /**
- * ...
- */
- protected void buildInitialFactories() {
- //Set Captcha Word Length Limitation which should not over 6
- Integer minAcceptedWordLength = new Integer(4);
- Integer maxAcceptedWordLength = new Integer(5);
- //Set up Captcha Image Size: Height and Width
- Integer imageHeight = new Integer(40);
- Integer imageWidth = new Integer(100);
- //Set Captcha Font Size
- Integer minFontSize = new Integer(20);
- Integer maxFontSize = new Integer(22);
- //We just generate digit for captcha source char Although you can use
- //abcdefg......xyz
- WordGenerator wordGenerator
- = new RandomWordGenerator("023456789");
- //cyt and unruledboy proved that backgroup not a factor of Security. A
- //captcha attacker won't affaid colorful backgroud, so we just use white
- //color, like google and hotmail.
- BackgroundGenerator backgroundGenerator = new GradientBackgroundGenerator(
- imageWidth, imageHeight, Color.white, Color.white);
- //font is not helpful for security but it really increase difficultness for
- //attacker
- FontGenerator fontGenerator = new RandomFontGenerator(minFontSize,
- maxFontSize);
- // Note that our captcha color is Blue
- SingleColorGenerator scg = new SingleColorGenerator(Color.blue);
- //decorator is very useful pretend captcha attack. we use two line text
- //decorators.
- LineTextDecorator lineDecorator = new LineTextDecorator(1, Color.blue);
- // LineTextDecorator line_decorator2 = new LineTextDecorator(1, Color.blue);
- TextDecorator[] textdecorators = new TextDecorator[1];
- textdecorators[0] = lineDecorator;
- // textdecorators[1] = line_decorator2;
- TextPaster textPaster = new DecoratedRandomTextPaster(
- minAcceptedWordLength, maxAcceptedWordLength, scg,
- new TextDecorator[] { new BaffleTextDecorator(new Integer(1),
- Color.white) });
- //ok, generate the WordToImage Object for logon service to use.
- WordToImage wordToImage = new ComposedWordToImage(
- fontGenerator, backgroundGenerator, textPaster);
- addFactory(new GimpyFactory(wordGenerator, wordToImage));
- }
- }
(3)ImageCaptchaServlet 类
- package cn.hxex.order.core.jcaptcha;
- 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;
- import org.apache.commons.lang.StringUtils;
- import org.springframework.context.ApplicationContext;
- import org.springframework.web.context.support.WebApplicationContextUtils;
- 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 java.awt.image.BufferedImage;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- /**
- * Servlet generates CAPTCHA jpeg images based on the JCAPTCHA package. It's
- * configured via spring, and requires a ImageCaptchaService bean with the
- * id=imageCaptchaService
- * 基于JCAPTCHA生成CAPTCHA jpeg图片的Servlet。它通过Spring进行配置,并且set一个
- * 类型为ImageCaptchaService,id为imageCaptchaService的bean
- * @author Jason Thrasher
- */
- @SuppressWarnings("serial")
- public class ImageCaptchaServlet extends HttpServlet {
- /**
- * Captcha Service Name
- */
- private String captchaServiceName = "imageCaptchaService";
- /**
- * @see HttpServlet#init(ServletConfig)
- */
- public void init(ServletConfig servletConfig) throws ServletException {
- if (StringUtils.isNotBlank(servletConfig
- .getInitParameter("captchaServiceName"))) {
- captchaServiceName = servletConfig.getInitParameter("captchaServiceName");
- }
- super.init(servletConfig);
- }
- /**
- * @see HttpServlet#doGet()
- */
- protected void doGet(HttpServletRequest httpServletRequest,
- HttpServletResponse httpServletResponse) throws ServletException,
- IOException {
- byte[] captchaChallengeAsJpeg = null;
- // the output stream to render the captcha image as jpeg into
- ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
- try {
- // get the image captcha service defined via the SpringFramework
- ApplicationContext ctx = WebApplicationContextUtils
- .getRequiredWebApplicationContext(getServletContext());
- Object bean = ctx.getBean(captchaServiceName);
- ImageCaptchaService imageCaptchaService = (ImageCaptchaService) bean;
- // 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 = httpServletRequest.getSession().getId();
- // call the ImageCaptchaService getChallenge method
- BufferedImage challenge = imageCaptchaService.getImageChallengeForID(
- captchaId, httpServletRequest.getLocale());
- // a jpeg encoder
- JPEGImageEncoder jpegEncoder = JPEGCodec
- .createJPEGEncoder(jpegOutputStream);
- jpegEncoder.encode(challenge);
- } catch (IllegalArgumentException e) {
- httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
- return;
- } catch (CaptchaServiceException e) {
- httpServletResponse
- .sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- return;
- }
- captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
- // flush it in the response
- httpServletResponse.setHeader("Cache-Control", "no-store");
- httpServletResponse.setHeader("Pragma", "no-cache");
- httpServletResponse.setDateHeader("Expires", 0);
- httpServletResponse.setContentType("image/jpeg");
- ServletOutputStream responseOutputStream = httpServletResponse
- .getOutputStream();
- responseOutputStream.write(captchaChallengeAsJpeg);
- responseOutputStream.flush();
- responseOutputStream.close();
- }
- }
(4)JCaptchaServiceProxyImpl 类
- package cn.hxex.order.core.jcaptcha;
- import com.octo.captcha.service.CaptchaService;
- import com.octo.captcha.service.CaptchaServiceException;
- import org.acegisecurity.captcha.CaptchaServiceProxy;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- /**
- * 实现 CaptchaServiceProxy 用于acegi来校验,由spring注入jcaptchaService
- *
- * @author sshwsfc@gmail.com
- */
- public class JCaptchaServiceProxyImpl implements CaptchaServiceProxy {
- /**
- * Log for the class
- */
- protected static Log log = LogFactory.getLog(JCaptchaServiceProxyImpl.class);
- /**
- * instance of CaptchaService.
- */
- private CaptchaService jcaptchaService;
- /**
- * @see {@link CaptchaServiceProxy#validateReponseForId(String, Object)}
- */
- public boolean validateReponseForId(String id, Object response) {
- log.debug("validating captcha response");
- try {
- boolean isHuman = jcaptchaService.validateResponseForID(id, response)
- .booleanValue();
- if (isHuman) {
- log.debug("captcha passed");
- } else {
- log.warn("captcha failed");
- }
- return isHuman;
- } catch (CaptchaServiceException cse) {
- // fixes known bug in JCaptcha
- log.warn("captcha validation failed due to exception", cse);
- return false;
- }
- }
- public void setJcaptchaService(CaptchaService jcaptchaService) {
- this.jcaptchaService = jcaptchaService;
转自:http://blog.csdn.net/jizhengjieing/article/details/6799261
相关推荐
Java JCaptcha验证码生成详解 验证码(CAPTCHA)是一种防止机器自动操作的安全机制,它通过让用户输入图片或音频中显示的随机字符来验证用户是否为真实的人。在Java开发中,JCaptcha是一个广泛使用的开源库,它提供...
总的来说,jcaptcha验证码所需jar包提供了一套完整的Java验证码解决方案,包含了处理HTTP请求的过滤器、日志记录工具以及核心的验证码生成和验证库。通过这些组件,开发者可以轻松地在Java Web应用中实现安全、可靠...
本文将深入探讨JCaptcha这个开源组件,它是Java环境下实现验证码生成的一个优秀工具。 JCaptcha(Java CAPTCHA)是一款强大的、可定制的验证码解决方案,由Gregg Sporar开发。它的主要目标是提供一种简单、高效的...
jcaptcha-2.0-alpha-1-SNAPSHOT.jar,jcaptcha-api-1.0.jar,jcaptcha-integration-simple-servlet-2.0-alpha-1-SNAPSHOT.jar
**jcaptcha验证码程序详解** 验证码(CAPTCHA)是一种防止机器自动操作的安全机制,它通过让用户识别并输入图片中的字符来验证用户是否为真人。在Java开发中,`jcaptcha`是一个广泛使用的开源库,用于生成复杂的...
在JSP下,用jcaptcha生成彩色验证码的案例。 主页http://jcaptcha.sourceforge.net/ 网上有很多例子,但有一点没说清楚,这个项目的jar包需要两个apache的项目包,一个是collections,还有一个是logging。 我做了...
JCAPTCHA提供了丰富的功能,包括生成复杂度高的图像验证码,确保只有人类用户能够正确识别。它的工作原理是通过生成随机的、难以被计算机程序识别的图像,然后要求用户输入看到的内容,以此来验证用户是否为真人。 ...
使用jcaptcha实现CAS中的验证码功能
在IT领域,`jCaptcha`(Just Another CAPTCHA)是一个非常流行的Java实现的验证码库,它提供了高度可定制的图像和音频验证码生成器。本文将详细介绍`jCaptcha`在基于`Acegi`安全框架的应用中的使用,以及如何设置一...
Java 通过 JCaptcha 生成验证码是一项常见的安全技术,用于防止自动化程序(如机器人)非法访问或操作网站。验证码,全称“全自动区分计算机和人类的图灵测试”,是一种验证用户是否为人类的方法。在此,我们将深入...
Jcaptcha(Java 验证码生成框架)使用说明 一、框架概述 Jcaptcha 是一个 Java 验证码生成框架,提供了详细的说明及例程,通过调查实践后,总结的,希望对大家有帮助。该框架提供了生成验证码图像通用解决办法,...
Jcaptcha,全称为“Java CAPTCHA”,是Java平台上一个开源的验证码库,它提供了一种生成复杂彩色图像验证码的方法,有助于提升网站的安全性。 本实例将深入讲解如何在Java环境中使用Jcaptcha库创建并部署彩色验证码...
jCaptcha是Java验证码解决方案的一个开源项目,它提供了丰富的功能和自定义选项,使得开发者能够轻松地在Web应用中集成验证码服务。jCaptcha-1.0-all.jar是这个项目的完整打包文件,包含了所有必要的类和库,可以...
Java验证码组件Jcaptcha是用于生成安全、动态的图像验证码的工具,主要目的是为了防止自动化的机器人或恶意软件在Web应用程序中进行非法操作,如批量注册、登录等。它通过生成随机字符组合并扭曲图像背景来增加人眼...
在这个名为“jcaptcha 彩色验证码-下载即可使用”的项目中,我们聚焦于一个特定的验证码实现:jCaptcha。jCaptcha 是一个基于 Java 的开源验证码库,它提供了丰富的图形验证码解决方案。这个库的特点在于可以创建...
根据提供的文件信息,本文将详细介绍如何使用 Spring Security 和 JCaptcha 框架来搭建一个包含验证码功能的安全系统。 ### 一、Spring Security简介 Spring Security 是一个强大的且高度可定制的身份验证和访问...
而jCaptcha(Just Another CAPTCHA)是一个开源的验证码生成库,它提供了一种有效的方式来生成复杂的验证码图像,从而增加网站的安全性。 在"通过spring整合jcaptcha来处理验证码"这个主题中,我们需要理解以下几个...
在本文中,我们将深入探讨如何在JFinal项目中集成并实现JCaptcha验证码功能。JCaptcha(Just Another CAPTCHA)是一个开源的Java验证码库,它提供了一种生成图像验证码的方法,可以有效防止自动化脚本和机器人对网站...
springsecurity3和JCaptcha的整合 验证码
在Java开发中,Jcaptcha(Just Another CAPTCHA)是一个强大的开源验证码库,它提供了一种简单易用的方式来生成和验证这些复杂的图像验证码。 Jcaptcha的核心功能包括生成随机且难以自动识别的图形验证码,以及验证...