jcaptcha验证码开源组件官方教程

来源:互联网 发布:关于网络的好处 编辑:程序博客网 时间:2024/05/19 13:09

1、简介

jcapthca是非常强大的,不光是可以生成图片式的验证码,还可以生成声音式的(新浪就使用了双重验证码)。

25分钟快速学会的例子

https://jcaptcha.atlassian.net/wiki/display/general/5+minutes+application+integration+tutorial

官方的这个例子很简单,用了最简单的组件,也就是默认的captchaservice,生成的验证码也是最简单的,官方的看不懂就看别人引用的吧

http://www.iteye.com/topic/567144

3、随便看看

具官方文档说,如果你不想用默认的,那么你就必须定制自己的captcha,可用的captchajavadoc列表,里面列出了很多东东。

还是先看一下具体有哪些captcha吧,网址:https://jcaptcha.atlassian.net/wiki/display/general/Samples+tests,这里就先截个图看看:


不止这些,最有趣的是还有声音验证码的。

具官方说明,一个验证码最好是这样的:


我就不翻译了。

接下来就是定制自己的component

针对上面的建议,它给出了很多具体你应该继承还是实现的类或者接口,具体看官网https://jcaptcha.atlassian.net/wiki/display/general/Proof+of+concept

4JCAPTCHASPRING集成

下面贴出与Spring集成的官方教程,严格按照IOC的方式,看了一下,基本能懂,太不科学了,我既然能看懂!!

Example of components widely used

This page show how to configure custom engine's components using Spring xml configuration.
Spring is not a requirement, you can use these components out of the box without Spring using their constructor.

See also : Change the Captcha generation configuration

· Example of components widely used

Base components

· Fonts

Color generators

· Single color

· List of colors

· Range of colors

· Locales

Special components

· Backgrounds

· Deformations

Configuration example

· ImageCaptchaFactories.xml

· ImageCaptchaService.xml

Base components

Fonts

<beanid="fontArial"class="java.awt.Font">

            <constructor-argindex="0"><value>Arial</value></constructor-arg>

            <constructor-argindex="1"><value>0</value></constructor-arg>

            <constructor-argindex="2"><value>10</value></constructor-arg>

        </bean>

 

        <beanid="fontTahoma"class="java.awt.Font">

            <constructor-argindex="0"><value>Tahoma</value></constructor-arg>

            <constructor-argindex="1"><value>0</value></constructor-arg>

            <constructor-argindex="2"><value>10</value></constructor-arg>

        </bean>

 

        <beanid="fontVerdana"class="java.awt.Font">

            <constructor-argindex="0"><value>Verdana</value></constructor-arg>

            <constructor-argindex="1"><value>0</value></constructor-arg>

            <constructor-argindex="2"><value>10</value></constructor-arg>

        </bean>

 

        <beanid="fontComic"class="java.awt.Font">

            <constructor-argindex="0"><value>Comic sans MS</value></constructor-arg>

            <constructor-argindex="1"><value>0</value></constructor-arg>

            <constructor-argindex="2"><value>10</value></constructor-arg>

        </bean>

 

        <beanid="fontLucida"class="java.awt.Font">

            <constructor-argindex="0"><value>Lucida console</value></constructor-arg>

            <constructor-argindex="1"><value>0</value></constructor-arg>

            <constructor-argindex="2"><value>10</value></constructor-arg>

        </bean>

Color generators

Single color

<beanid="colorGenYellow"class="com.octo.captcha.component.image.color.SingleColorGenerator">

        <constructor-argindex="0"><refbean="yellow"/></constructor-arg>

</bean>

List of colors

<beanid="colorGenRandomList"class="com.octo.captcha.component.image.color.RandomListColorGenerator">

        <constructor-argindex="0">

            <list>

                <refbean="yellow"/>

                <refbean=" blue "/>

                <refbean=" lightBlue "/>

            </list>

        </constructor-arg>

    </bean>

    <beanid="blue"class="java.awt.Color">

        <constructor-argtype="int"index="0"><value>0</value></constructor-arg>

        <constructor-argtype="int"index="1"><value>0</value></constructor-arg>

        <constructor-argtype="int"index="2"><value>255</value></constructor-arg>

    </bean>

 

    <beanid="lightBlue"class="java.awt.Color">

        <constructor-argtype="int"index="0"><value>200</value></constructor-arg>

        <constructor-argtype="int"index="1"><value>200</value></constructor-arg>

        <constructor-argtype="int"index="2"><value>255</value></constructor-arg>

    </bean>

 

    <beanid="yellow"class="java.awt.Color">

        <constructor-argtype="int"index="0"><value>255</value></constructor-arg>

        <constructor-argtype="int"index="1"><value>255</value></constructor-arg>

        <constructor-argtype="int"index="2"><value>0</value></constructor-arg>

    </bean>

Range of colors

<beanid="colorGenRandomBlue"class="com.octo.captcha.component.image.color.RandomRangeColorGenerator">

        <constructor-argindex="0">

        <list>

          <value>150</value>

          <value>255</value>

        </list>

        </constructor-arg>

        <constructor-argindex="1">

        <list>

          <value>0</value>

          <value>50</value>

        </list>

        </constructor-arg>

        <constructor-argindex="2">

        <list>

          <value>200</value>

          <value>255</value>

        </list>

        </constructor-arg>

        <constructor-argindex="3">

        <list>

          <value>255</value>

          <value>255</value>

        </list>

        </constructor-arg>

    </bean>

Locales

<beanid="java.util.Locale.FRANCE"

      class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"/>

 <beanid="java.util.Locale.US"

      class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"/>

Special components

Backgrounds

<beanid="backGenUni"class="com.octo.captcha.component.image.backgroundgenerator.UniColorBackgroundGenerator">

        <constructor-argindex="0"><value>300</value></constructor-arg>

        <constructor-argindex="1"><value>100</value></constructor-arg>

</bean>

 

<beanid="backGenFunky"class="com.octo.captcha.component.image.backgroundgenerator.FunkyBackgroundGenerator">

        <constructor-argindex="0"><value>300</value></constructor-arg>

        <constructor-argindex="1"><value>100</value></constructor-arg>

        <constructor-argtype="com.octo.captcha.component.image.color.ColorGenerator"index="2"><ref               bean="colorGenRandomList"/></constructor-arg>

        <constructor-argtype="com.octo.captcha.component.image.color.ColorGenerator"index="3"><ref               bean="colorGenRandomList"/></constructor-arg>

        <constructor-argtype="com.octo.captcha.component.image.color.ColorGenerator"index="4"><ref               bean="colorGenRandomList"/></constructor-arg>

        <constructor-argtype="com.octo.captcha.component.image.color.ColorGenerator"index="5"><ref           bean="colorGenRandomList"/></constructor-arg>

        <constructor-argindex="6"><value>0.2f</value></constructor-arg>

    </bean>

 

 

    <beanid="backGenMultiShape"       class="com.octo.captcha.component.image.backgroundgenerator.MultipleShapeBackgroundGenerator" >

        <constructor-argindex="0"><value>300</value></constructor-arg>

        <constructor-argindex="1"><value>100</value></constructor-arg>

        <!--firstEllipseColorGenerator-->

        <constructor-argindex="2"><refbean="lightBlue"/></constructor-arg>

        <!--secondEllipseColorGenerator-->

        <constructor-argindex="3"><refbean="lightRed"/></constructor-arg>

        <!--spaceBetweenLine-->

        <constructor-argindex="4"><value>10</value></constructor-arg>

        <!--spaceBetweenCircle-->

        <constructor-argindex="5"><value>5</value></constructor-arg>

        <!--ellipseHeight-->

        <constructor-argindex="6"><value>10</value></constructor-arg>

        <!--ellipseWidth-->

        <constructor-argindex="7"><value>6</value></constructor-arg>

        <!--firstRectangleColorGenerator-->

        <constructor-argindex="8"><refbean="red"/></constructor-arg>

        <!--secondRectangleColorGenerator-->

        <constructor-argindex="9"><refbean="white"/></constructor-arg>

        <!--firstRectangleColorGenerator-->

        <constructor-argindex="10"><value>3</value></constructor-arg>

    </bean>

 

    <beanid="backGenPicture"      class="com.octo.captcha.component.image.backgroundgenerator.FileReaderRandomBackgroundGenerator" >

        <constructor-argindex="0"><value>300</value></constructor-arg>

        <constructor-argindex="1"><value>100</value></constructor-arg>

        <constructor-argindex="2"><refbean="path"/></constructor-arg>

    </bean>

 

    <beanid="path"class="java.lang.String">

        <constructor-arg><value>\home\jcaptcha\conf\gimpybackgrounds</value></constructor-arg>

    </bean>

Deformations

Deformations can be build with ImageFilter, like JhLabs Filtres, and injected in a ImageDeformationByFilters component.

<beanid="sphere"class="com.jhlabs.image.SphereFilter">

            <propertyname="refractionIndex"><value>1</value></property>

        </bean>

 

        <beanid="emboss"class="com.jhlabs.image.EmbossFilter">

            <propertyname="bumpHeight"><value>1.0</value></property>

        </bean>

 

        <beanid="rippleBack"class="com.jhlabs.image.RippleFilter">

            <propertyname="waveType"><value>3</value></property>

            <propertyname="XAmplitude"><value>10</value></property>

            <propertyname="YAmplitude"><value>3</value></property>

            <propertyname="XWavelength"><value>20</value></property>

            <propertyname="YWavelength"><value>10</value></property>

            <propertyname="edgeAction"><value>1</value></property>

        </bean>

 

        <beanid="smear"class="com.jhlabs.image.SmearFilter">

            <propertyname="shape"><value>0</value></property>

            <propertyname="distance"><value>15</value></property>

            <propertyname="density"><value>0.4</value></property>

            <propertyname="scatter"><value>0.5</value></property>

            <propertyname="angle"><value>0.0</value></property>

            <propertyname="mix"><value>0.6</value></property>

            <propertyname="fadeout"><value>0</value></property>

        </bean>

 

        <beanid="ripple"class="com.jhlabs.image.RippleFilter">

            <propertyname="waveType"><value>1</value></property>

            <propertyname="XAmplitude"><value>2</value></property>

            <propertyname="YAmplitude"><value>2</value></property>

            <propertyname="XWavelength"><value>10</value></property>

            <propertyname="YWavelength"><value>10</value></property>

            <propertyname="edgeAction"><value>1</value></property>

        </bean>

 

        <beanid="ripple2"class="com.jhlabs.image.RippleFilter">

            <propertyname="waveType"><value>2</value></property>

            <propertyname="XAmplitude"><value>2</value></property>

            <propertyname="YAmplitude"><value>2</value></property>

            <propertyname="XWavelength"><value>10</value></property>

            <propertyname="YWavelength"><value>10</value></property>

            <propertyname="edgeAction"><value>1</value></property>

        </bean>

 

        <beanid="ripple3"class="com.jhlabs.image.RippleFilter">

            <propertyname="waveType"><value>5</value></property>

            <propertyname="XAmplitude"><value>5</value></property>

            <propertyname="YAmplitude"><value>5</value></property>

            <propertyname="XWavelength"><value>10</value></property>

            <propertyname="YWavelength"><value>10</value></property>

            <propertyname="edgeAction"><value>1</value></property>

        </bean>

 

 

        <beanid="twirl"class="com.jhlabs.image.TwirlFilter">

            <propertyname="angle"><value>0.8</value></property>

        </bean>

 

        <beanid="water"class="com.jhlabs.image.WaterFilter">

            <propertyname="amplitude"><value>2</value></property>

            <propertyname="antialias"><value>true</value></property>

            <propertyname="wavelength"><value>20</value></property>

        </bean>

 

        <beanid="weaves"class="com.jhlabs.image.WeaveFilter">

            <propertyname="useImageColors"><value>true</value></property>

            <propertyname="XGap"><value>2</value></property>

            <propertyname="XWidth"><value>10</value></property>

            <propertyname="YWidth"><value>16</value></property>

            <propertyname="YGap"><value>6</value></property>

        </bean>

 

 

        <beanid="crystal"class="com.jhlabs.image.CrystalizeFilter">

            <propertyname="scale"><value>0.5</value></property>

            <propertyname="gridType"><value>1</value></property>

            <propertyname="fadeEdges"><value>false</value></property>

            <propertyname="edgeThickness"><value>0.4</value></property>

            <propertyname="randomness"><value>1.0</value></property>

        </bean>

 

        <beanid="smearDef"class="com.octo.captcha.component.image.deformation.ImageDeformationByFilters">

            <constructor-argindex="0">

                <list>

                    <refbean="smear"/>

                </list>

            </constructor-arg>

        </bean>

 

        <beanid="rippleDef"class="com.octo.captcha.component.image.deformation.ImageDeformationByFilters">

            <constructor-argindex="0">

                <list>

                    <refbean="ripple"/>

                </list>

            </constructor-arg>

        </bean>

 

        <beanid="ripple2Def"class="com.octo.captcha.component.image.deformation.ImageDeformationByFilters">

            <constructor-argindex="0">

                <list>

                    <refbean="ripple2"/>

                </list>

            </constructor-arg>

        </bean>

 

        <beanid="ripple3Def"class="com.octo.captcha.component.image.deformation.ImageDeformationByFilters">

            <constructor-argindex="0">

                <list>

                    <refbean="ripple3"/>

                </list>

            </constructor-arg>

        </bean>

 

 

        <beanid="sphereDef"class="com.octo.captcha.component.image.deformation.ImageDeformationByFilters">

            <constructor-argindex="0">

                <list>

                    <refbean="sphere"/>

                </list>

            </constructor-arg>

        </bean>

 

        <beanid="waterDef"class="com.octo.captcha.component.image.deformation.ImageDeformationByFilters">

            <constructor-argindex="0">

                <list>

                    <refbean="water"/>

                </list>

            </constructor-arg>

        </bean>

 

        <beanid="embossDef"class="com.octo.captcha.component.image.deformation.ImageDeformationByFilters">

            <constructor-argindex="0">

                <list>

                    <refbean="emboss"/>

                </list>

            </constructor-arg>

        </bean>

 

        <beanid="rippleDefBack"class="com.octo.captcha.component.image.deformation.ImageDeformationByFilters">

            <constructor-argindex="0">

                <list>

                    <refbean="rippleBack"/>

                </list>

            </constructor-arg>

        </bean>

 

        <beanid="cristalDef"class="com.octo.captcha.component.image.deformation.ImageDeformationByFilters">

            <constructor-argindex="0">

                <list>

                    <refbean="crystal"/>

                </list>

            </constructor-arg>

        </bean>

 

        <beanid="weavesDef"class="com.octo.captcha.component.image.deformation.ImageDeformationByFilters">

            <constructor-argindex="0">

                <list>

                    <refbean="weaves"/>

                </list>

            </constructor-arg>

        </bean>

 

        <beanid="twirlDef"class="com.octo.captcha.component.image.deformation.ImageDeformationByFilters">

            <constructor-argindex="0">

                <list>

                    <refbean="twirl"/>

                </list>

            </constructor-arg>

        </bean>

 

        <beanid="none"class="com.octo.captcha.component.image.deformation.ImageDeformationByFilters">

            <constructor-argindex="0">

                <null/>

            </constructor-arg>

        </bean>

Configuration example

This jcaptcha configuration using spring embeded two configurations files :
The first one configures ImageCaptchaFactories
The second one configures ImageCaptchaEngine and ImageCaptchaService

ImageCaptchaFactories.xml

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "<a href="http://www.springframework.org/dtd/spring-beans.dtd" "="" style="color: rgb(50, 108, 166); text-decoration: initial; border-top-left-radius: 0px !important; border-top-right-radius: 0px !important; border-bottom-right-radius: 0px !important; border-bottom-left-radius: 0px !important; background-image: none !important; border: 0px !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; margin: 0px !important; outline: 0px !important; overflow: visible !important; padding: 0px !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; width: auto !important; box-sizing: content-box !important; min-height: auto !important;">http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

 

 

 

<!-- ************ FACTORIES declaration  ************-->

 

        <!-- Constructs a captcha factory which produce captcha,

         from a word generator (the content) and a word to image (the representation)-->

 

        <beanid="imageCaptchaFactory"class="com.octo.captcha.image.gimpy.GimpyFactory">

            <constructor-arg><refbean="wordgen"/></constructor-arg>

            <constructor-arg><refbean="wordtoimage"/></constructor-arg>

        </bean>

 

 

 

<!-- ************ WORD 2 IMAGE declaration  ************-->

 

        <!-- Constructs a WordToImage, which assemble components: a font generator,

             a background generator, a paster and deformations:

             the fist one deform the background only (none is the "null" deformation, which does nothing)

             the second one deform the text only (none is the "null" deformation, which does nothing)

             the third one deform the hole picture

             -->

        <beanid="wordtoimage"class="com.octo.captcha.component.image.wordtoimage.ComposedWordToImage">

            <constructor-argindex="0"><refbean="fontGenRandom"/></constructor-arg>

            <constructor-argindex="1"><refbean="backGenUni"/></constructor-arg>

            <constructor-argindex="2"><refbean="simpleColoredPaster"/></constructor-arg>

<!--         <constructor-arg index="3"><ref bean="none"/></constructor-arg>-->

<!--         <constructor-arg index="4"><ref bean="none"/></constructor-arg>-->

<!--         <constructor-arg index="5"><ref bean="ripple3Def"/></constructor-arg>-->

        </bean>

 

 <!-- ************ BACKGROUND declaration  ************-->

 

        <!-- Constructs a background generator,

            this one is the default Unicolor, white is background color -->

        <beanid="backGenUni"class="com.octo.captcha.component.image.backgroundgenerator.UniColorBackgroundGenerator">

                        <constructor-argindex="0"><value>300</value></constructor-arg>

                        <constructor-argindex="1"><value>100</value></constructor-arg>

        </bean>

 

<!-- ************ FONT  declaration  ************-->

 

        <beanid="fontArial"class="java.awt.Font">

            <constructor-argindex="0"><value>Arial</value></constructor-arg>

            <constructor-argindex="1"><value>0</value></constructor-arg>

            <constructor-argindex="2"><value>10</value></constructor-arg>

        </bean>

 

        <beanid="fontTahoma"class="java.awt.Font">

            <constructor-argindex="0"><value>Tahoma</value></constructor-arg>

            <constructor-argindex="1"><value>0</value></constructor-arg>

            <constructor-argindex="2"><value>10</value></constructor-arg>

        </bean>

 

        <beanid="fontVerdana"class="java.awt.Font">

            <constructor-argindex="0"><value>Verdana</value></constructor-arg>

            <constructor-argindex="1"><value>0</value></constructor-arg>

            <constructor-argindex="2"><value>10</value></constructor-arg>

        </bean>

 

        <beanid="fontComic"class="java.awt.Font">

            <constructor-argindex="0"><value>Comic sans MS</value></constructor-arg>

            <constructor-argindex="1"><value>0</value></constructor-arg>

            <constructor-argindex="2"><value>10</value></constructor-arg>

        </bean>

 

        <beanid="fontLucida"class="java.awt.Font">

            <constructor-argindex="0"><value>Lucida console</value></constructor-arg>

            <constructor-argindex="1"><value>0</value></constructor-arg>

            <constructor-argindex="2"><value>10</value></constructor-arg>

        </bean>

<!-- ************ FONT GENERATOR declaration  ************-->

 

        <!-- Constructs Font generator, with the min and max size of font,

            and with a list of fonts-->

        <beanid="fontGenRandom"class="com.octo.captcha.component.image.fontgenerator.RandomFontGenerator">

                        <constructor-argindex="0"><value>40</value></constructor-arg>

                        <constructor-argindex="1"><value>50</value></constructor-arg>

                        <constructor-argindex="2">

                                <list>

                                    <refbean="fontArial"/>

                                    <refbean="fontTahoma"/>

                                    <refbean="fontVerdana"/>

                                    <refbean="fontComic"/>

                                    <refbean="fontLucida"/>

                                </list>

                        </constructor-arg>

        </bean>

 

<!-- ************ PASTER declaration  ************-->

 

        <!-- Constructs the paster component, a baffle one, which make holes in characters

            Parameters :

            int for the min length of the word

            int for the max length of the word

            ColorGenerator for the color of the word

            boolean to know if each character can have a different color

            -->

        <beanid="simpleColoredPaster"class="com.octo.captcha.component.image.textpaster.RandomTextPaster">

                        <constructor-argtype="java.lang.Integer"index="0"><value>4</value></constructor-arg>

                        <constructor-argtype="java.lang.Integer"index="1"><value>6</value></constructor-arg>

                        <constructor-argtype="com.octo.captcha.component.image.color.ColorGenerator"index="2"><refbean="colorGenRandomDark"/></constructor-arg>

                        <constructor-argindex="3"><value>true</value></constructor-arg>

        </bean>

 

 

<!-- ************ DIC and WORD GENERATOR declaration  ************-->

 

        <!-- Constructs a File diconnary, which will read words from a file, corresponding to Locle (for instance with locale France,

             it will look for the file : toddlist_fr_FR.properties, if not found, take toddlist.properties -->

        <beanid="filedict"class="com.octo.captcha.component.wordgenerator.FileDictionnary">

            <constructor-argindex="0"><value>toddlist</value></constructor-arg>

        </bean>

 

    <!-- <bean id="wordgen" class="com.octo.captcha.component.wordgenerator.DictionaryWordGenerator" >

            <constructor-arg><ref bean="filedict"/></constructor-arg>

        </bean>-->

 

        <!-- Constructs a word generator, which composed words from existing words

            It takes a diconnary for the existing words-->

        <beanid="wordgen"class="com.octo.captcha.component.wordgenerator.ComposeDictionaryWordGenerator">

            <constructor-arg><refbean="filedict"/></constructor-arg>

        </bean>

 

<!-- ************ FILTER  declaration  ************-->

 

        <!-- Constructs the "null" deformation component-->

        <beanid="none"class="com.octo.captcha.component.image.deformation.ImageDeformationByFilters">

            <constructor-argindex="0">

                <null/>

            </constructor-arg>

        </bean>

 

<!-- ************ COLORS Declarations ************-->

 

        <!-- Constructs a java Color-->

        <beanid="white"class="java.awt.Color">

            <constructor-argtype="int"index="0"><value>255</value></constructor-arg>

            <constructor-argtype="int"index="1"><value>255</value></constructor-arg>

            <constructor-argtype="int"index="2"><value>255</value></constructor-arg>

        </bean>

 

        <!-- Constructs a color generator which generate one color -->

        <beanid="colorGenWhite"class="com.octo.captcha.component.image.color.SingleColorGenerator">

            <constructor-argindex="0"><refbean="white"/></constructor-arg>

        </bean>

 

        <!-- Constructs a color generator which generate dark color correspond to the different ranges-->

        <beanid="colorGenRandomDark"class="com.octo.captcha.component.image.color.RandomRangeColorGenerator">

            <constructor-argindex="0">

                <list>

                    <value>0</value>

                    <value>150</value>

                </list>

            </constructor-arg>

            <constructor-argindex="1">

                <list>

                    <value>0</value>

                    <value>150</value>

                </list>

            </constructor-arg>

            <constructor-argindex="2">

                <list>

                    <value>0</value>

                    <value>150</value>

                </list>

            </constructor-arg>

            <constructor-argindex="3">

                <list>

                    <value>255</value>

                    <value>255</value>

                </list>

            </constructor-arg>

        </bean>

 

 

 

 

</beans>

ImageCaptchaService.xml

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "<a href="http://www.springframework.org/dtd/spring-beans.dtd" "="" style="color: rgb(50, 108, 166); text-decoration: initial; border-top-left-radius: 0px !important; border-top-right-radius: 0px !important; border-bottom-right-radius: 0px !important; border-bottom-left-radius: 0px !important; background-image: none !important; border: 0px !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; margin: 0px !important; outline: 0px !important; overflow: visible !important; padding: 0px !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; width: auto !important; box-sizing: content-box !important; min-height: auto !important;">http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

 

 

<!-- Constructs a captcha engine, with custom factories-->

    <bean

        class="com.octo.captcha.engine.GenericCaptchaEngine"id="imageEngine">

        <constructor-argindex="0">

                <list>

                    <refbean="imageCaptchaFactory"/>

                </list>

        </constructor-arg>

    </bean>

 

    <beanid="imageCaptchaService"

        class="com.octo.captcha.service.multitype.GenericManageableCaptchaService">

        <constructor-argindex="0">

            <refbean="imageEngine"/>

        </constructor-arg>

        <constructor-argindex="1"><value>300</value></constructor-arg>

        <constructor-argindex="2"><value>200000</value></constructor-arg>

    </bean>

</beans>

6JCaptcha and the SpringFramework

还有一些comments,也是很不错的

Introduction 

JCaptcha tries to strictly respect the Inversion of Control pattern, to ease creation of components for concrete applications. 
On the other side the Spring Framework allows to use the power of IOC combined with XML declarations.
So that, every single component of jCaptcha can be declared in XML, and instanced through Spring.
An application using jCaptcha should only manipulate a CaptchaService instance.

5-second configuration

The simplest configuration possible is to declare the following in your Spring context

<beanclass="com.octo.captcha.service.image.DefaultManageableImageCaptchaService"id="imageCaptchaService"/>

10-seconds configuration

Showing how to change the default engine, for getting diferent captchas:

<beanid="captchaEngine"class="com.octo.captcha.engine.image.gimpy.SimpleListImageCaptchaEngine"/>

<beanid="captchaService"class="com.octo.captcha.service.image.DefaultManageableImageCaptchaService"

singleton="true">

<propertyname="captchaEngine"ref="captchaEngine"/>

</bean>

Now if you want to customize your engine configuration, you'll need to define your own implementation

Setting a captcha custom service and engine configuration in Spring

In this section we will describe how to set components to create a full CaptchaEngine.

We will start with what we want, the CaptchaEngine, for each component we provide a working and common example, but every component has several implementations, see the Java doc for more details. The construction of each component in XML must respect a constructor of this component.

There are several Engines pre-configured, but as we want to control configuration, we have to use the GenericCaptchaEngine, which is built with a list of captcha factories (factories are the ?real? producer of captchas)

<beanid="imageEngine"class="com.octo.captcha.engine.GenericCaptchaEngine">

    <constructor-argindex="0">

        <list>

            <refbean="CaptchaFactory"/>

        </list>

    </constructor-arg>

</bean>

Then, a CaptchaFactory needs:

· A word generator, to create the text to read.

· A wordToImage, to generate the captcha from the text.

<beanid="CaptchaFactory"class="com.octo.captcha.image.gimpy.GimpyFactory">

    <constructor-arg><refbean="wordgen"/></constructor-arg>

    <constructor-arg><refbean="wordtoimage"/></constructor-arg>

</bean>

A WordGenerator creates a text to be read, it can be random, be a common implementation take words from a list, and can make composition to create a text easier to read for a human being. In the example the WordGenerator needs a Dictionnary to get real words from.

<beanid="wordgen"class="com.octo.captcha.component.word.wordgenerator.DictionaryWordGenerator">

    <constructor-arg><refbean="filedict"/></constructor-arg>

</bean>

A Dictionary provides words, this one reads words from the one provided by default, with almost 6000 english words.

<beanid="filedict"class="com.octo.captcha.component.word.FileDictionary">

    <constructor-argindex="0"><value>toddlist</value></constructor-arg>

</bean>

After to other important part to create a factory, is the WordToImage component, which is mainly created with three others components:

· A font generator

· A background generator

· A Text paster

This example is a bit more complex one; it takes the usual main three components, but also three deformations, to increase the power of captchas. All three are set to none, a component which creates no deformation, see below, and Examples to have more examples of deformations.

<beanid="wordtoimage"class="com.octo.captcha.component.image.wordtoimage.ComposedWordToImage">

    <constructor-argindex="0"><refbean="fontGenRandom"/></constructor-arg>

    <constructor-argindex="1"><refbean="backGenUni"/></constructor-arg>

    <constructor-argindex="2"><refbean="simpleWhitePaster"/></constructor-arg>

</bean>

A FontGenerator provide Fonts to a WordToImage, differents fonts increase the difficulties for cracking software using a learning process. This one generates random fonts from a list, and the first two arguments are the minimum size and the maximum size of the font.

<beanid="fontGenRandom"class="com.octo.captcha.component.image.fontgenerator.RandomFontGenerator">

    <constructor-argindex="0"><value>40</value></constructor-arg>

    <constructor-argindex="1"><value>50</value></constructor-arg>

    <constructor-argindex="2">

        <list>

            <refbean="fontArial"/>

        </list>

    </constructor-arg>

</bean>

A font is declared like this :

<beanid="fontArial"class="java.awt.Font">

    <constructor-argindex="0"><value>Arial</value></constructor-arg>

    <constructor-argindex="1"><value>0</value></constructor-arg>

    <constructor-argindex="2"><value>10</value></constructor-arg>

</bean>

The BackgrountGenerator component can be very simple like in the example, single color, or more complex with real picture, or fancy computed shapes. The first two arguments are always, the size (length and height) of the resulting image.

<beanid="backGenUni"class="com.octo.captcha.component.image.backgroundgenerator.UniColorBackgroundGenerator">

    <constructor-argindex="0"><value>300</value></constructor-arg>

    <constructor-argindex="1"><value>100</value></constructor-arg>

</bean>

The TextPaster, according to his name, pastes the text on the background. This can be done in a simple way, (see example below), or another implementation can paste each character randomly (but still readably), or can double the text to make computers more confused. TextPaster can be even decorated to put perturbations around the text, a component, TextDecorator, is designed for this purpose, see Annexes for some examples. Commons arguments for TextPaster are:
1. Minimal length of the text
2. Maximal length of the text
3. A color generator component to create the text color, see Annexes.

<beanid="simpleWhitePaster"class="com.octo.captcha.component.image.textpaster.SimpleTextPaster">

    <constructor-argtype="java.lang.Integer"index="0">

        <value>3</value>

    </constructor-arg>

    <constructor-argtype="java.lang.Integer"index="1">

        <value>5</value>

    </constructor-arg>

    <constructor-argtype="java.awt.Color"index="2">

        <refbean="colorGreen"/>

    </constructor-arg>

</bean>

And a color definition:

<beanid="colorGreen"class="java.awt.Color">

    <constructor-argindex="0"><value>0</value></constructor-arg>

    <constructor-argindex="1"><value>255</value></constructor-arg>

    <constructor-argindex="2"><value>0</value></constructor-arg>

</bean>

Now we are ready to setup the CaptchaService singleton...

Setting the CaptchaService in Spring

This component has a special section because it is the top level component, which is actually manipulated within your application. As for the engine, there is many already configured CaptchaService, but the one we need is a custom one, which takes an CaptchaEngine, as you can see, the BufferedEngineContairner, is in fact CaptchaEngine.

The arg index1 is the captcha session expering time, in seconds. Next arg especifies the maximun storage size.

<beanid="captchaService"class="com.octo.captcha.service.multitype.GenericManageableCaptchaService">

    <constructor-argindex="0"><refbean="imageEngine"/></constructor-arg>

    <constructor-argindex="1"><value>180</value></constructor-arg>

    <constructor-argindex="2"><value>180000</value></constructor-arg>

</bean>

Other links, resources:

Please refers to External resources

· No labels

7 Comments

Anand

Can any one help me in integrating Jcaptcha with Spring and Acegi as I am new to these concepts. I have to implement security in my new project which uses Spring frame work.

· Jun 30, 2007

John Kostaras

Well,

more details regarding the 5-sec and 10-sec tutorials would be helpful. Could anyone explain to me why this doesn't work? I receive an empty captcha image.

 web.xml

<?xml version="1.0"encoding="UTF-8"?>

<web-app version="2.5"xmlns="<a href="http://java.sun.com/xml/ns/javaee" "="" style="color: rgb(50, 108, 166); text-decoration: initial; border-top-left-radius: 0px !important; border-top-right-radius: 0px !important; border-bottom-right-radius: 0px !important; border-bottom-left-radius: 0px !important; background-image: none !important; border: 0px !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; margin: 0px !important; outline: 0px !important; overflow: visible !important; padding: 0px !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; width: auto !important; box-sizing: content-box !important; min-height: auto !important;">http://java.sun.com/xml/ns/javaee"

                                    xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance" "="" style="color: rgb(50, 108, 166); text-decoration: initial; border-top-left-radius: 0px !important; border-top-right-radius: 0px !important; border-bottom-right-radius: 0px !important; border-bottom-left-radius: 0px !important; background-image: none !important; border: 0px !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; margin: 0px !important; outline: 0px !important; overflow: visible !important; padding: 0px !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; width: auto !important; box-sizing: content-box !important; min-height: auto !important;">http://www.w3.org/2001/XMLSchema-instance"

                                    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee <a href="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" "="" style="color: rgb(50, 108, 166); text-decoration: initial; border-top-left-radius: 0px !important; border-top-right-radius: 0px !important; border-bottom-right-radius: 0px !important; border-bottom-left-radius: 0px !important; background-image: none !important; border: 0px !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; margin: 0px !important; outline: 0px !important; overflow: visible !important; padding: 0px !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; width: auto !important; box-sizing: content-box !important; min-height: auto !important;">http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <context-param>

        <param-name>contextConfigLocation</param-name>

        <param-value>/WEB-INF/applicationContext.xml</param-value>

    </context-param>

    <context-param>

        <param-name>webAppRootKey</param-name>

        <param-value>captcha.root</param-value>

    </context-param>

 

    <listener>

        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>

    </listener>

    <listener>

        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

    </listener>

 

    <servlet>

        <servlet-name>dispatcher</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <load-on-startup>2</load-on-startup>

    </servlet>

 

    <servlet-mapping>

        <servlet-name>dispatcher</servlet-name>

        <url-pattern>*.htm</url-pattern>

    </servlet-mapping>

 

    <session-config>

        <session-timeout>30</session-timeout>

    </session-config>

 

    <welcome-file-list>

        <welcome-file>redirect.jsp</welcome-file>

    </welcome-file-list>

 

    <error-page>

        <exception-type>java.lang.Throwable</exception-type>

           <location>/error.html</location>

    </error-page>

</web-app>

dispatcher-servlet.xml

 <?xml version="1.0"encoding="UTF-8"?>

<beans xmlns="<a href="http://www.springframework.org/schema/beans" "="" style="color: rgb(50, 108, 166); text-decoration: initial; border-top-left-radius: 0px !important; border-top-right-radius: 0px !important; border-bottom-right-radius: 0px !important; border-bottom-left-radius: 0px !important; background-image: none !important; border: 0px !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; margin: 0px !important; outline: 0px !important; overflow: visible !important; padding: 0px !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; width: auto !important; box-sizing: content-box !important; min-height: auto !important;">http://www.springframework.org/schema/beans"

       xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance" "="" style="color: rgb(50, 108, 166); text-decoration: initial; border-top-left-radius: 0px !important; border-top-right-radius: 0px !important; border-bottom-right-radius: 0px !important; border-bottom-left-radius: 0px !important; background-image: none !important; border: 0px !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; margin: 0px !important; outline: 0px !important; overflow: visible !important; padding: 0px !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; width: auto !important; box-sizing: content-box !important; min-height: auto !important;">http://www.w3.org/2001/XMLSchema-instance"

       xmlns:p="<a href="http://www.springframework.org/schema/p" "="" style="color: rgb(50, 108, 166); text-decoration: initial; border-top-left-radius: 0px !important; border-top-right-radius: 0px !important; border-bottom-right-radius: 0px !important; border-bottom-left-radius: 0px !important; background-image: none !important; border: 0px !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; margin: 0px !important; outline: 0px !important; overflow: visible !important; padding: 0px !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; width: auto !important; box-sizing: content-box !important; min-height: auto !important;">http://www.springframework.org/schema/p"

       xmlns:aop="<a href="http://www.springframework.org/schema/aop" "="" style="color: rgb(50, 108, 166); text-decoration: initial; border-top-left-radius: 0px !important; border-top-right-radius: 0px !important; border-bottom-right-radius: 0px !important; border-bottom-left-radius: 0px !important; background-image: none !important; border: 0px !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; margin: 0px !important; outline: 0px !important; overflow: visible !important; padding: 0px !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; width: auto !important; box-sizing: content-box !important; min-height: auto !important;">http://www.springframework.org/schema/aop"

       xmlns:tx="<a href="http://www.springframework.org/schema/tx" "="" style="color: rgb(50, 108, 166); text-decoration: initial; border-top-left-radius: 0px !important; border-top-right-radius: 0px !important; border-bottom-right-radius: 0px !important; border-bottom-left-radius: 0px !important; background-image: none !important; border: 0px !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; margin: 0px !important; outline: 0px !important; overflow: visible !important; padding: 0px !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; width: auto !important; box-sizing: content-box !important; min-height: auto !important;">http://www.springframework.org/schema/tx"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

                           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

                           http://www.springframework.org/schema/aop

                           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

                           http://www.springframework.org/schema/tx

                           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

 

    <beanclass="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

<!--

    <bean id="captchaEngine"class="com.octo.captcha.engine.image.gimpy.SimpleListImageCaptchaEngine"/>

 

    <bean id="captchaService"name="/captcha.htm"

        class="com.octo.captcha.service.image.DefaultManageableImageCaptchaService">

        <property name="captchaEngine"ref="captchaEngine"/>

    </bean>

-->

    <bean name="/captcha.htm"class="com.octo.captcha.service.image.DefaultManageableImageCaptchaService"id="imageCaptchaService"/>

 

    <bean id="urlMapping"class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

        <property name="mappings">

            <props>

                <prop key="index.htm">indexController</prop>

            </props>

        </property>

    </bean>

 

    <bean id="viewResolver"

          class="org.springframework.web.servlet.view.InternalResourceViewResolver"

          p:prefix="/WEB-INF/jsp/"

          p:suffix=".jsp"/>

 

    <bean name="indexController"

          class="org.springframework.web.servlet.mvc.ParameterizableViewController"

          p:viewName="index"/>

 

</beans>

 index.jsp

<%@ page session="false"contentType="text/html; charset=utf-8"pageEncoding="utf-8"%>

<%@ taglib prefix="spring"uri="<a href="http://www.springframework.org/tags" "="" style="color: rgb(50, 108, 166); text-decoration: initial; border-top-left-radius: 0px !important; border-top-right-radius: 0px !important; border-bottom-right-radius: 0px !important; border-bottom-left-radius: 0px !important; background-image: none !important; border: 0px !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; margin: 0px !important; outline: 0px !important; overflow: visible !important; padding: 0px !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; width: auto !important; box-sizing: content-box !important; min-height: auto !important;">http://www.springframework.org/tags"%>

<%@ taglib prefix="c"uri="<a href="http://java.sun.com/jsp/jstl/core" "="" style="color: rgb(50, 108, 166); text-decoration: initial; border-top-left-radius: 0px !important; border-top-right-radius: 0px !important; border-bottom-right-radius: 0px !important; border-bottom-left-radius: 0px !important; background-image: none !important; border: 0px !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; margin: 0px !important; outline: 0px !important; overflow: visible !important; padding: 0px !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; width: auto !important; box-sizing: content-box !important; min-height: auto !important;">http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="f"uri="<a href="http://java.sun.com/jsp/jstl/fmt" "="" style="color: rgb(50, 108, 166); text-decoration: initial; border-top-left-radius: 0px !important; border-top-right-radius: 0px !important; border-bottom-right-radius: 0px !important; border-bottom-left-radius: 0px !important; background-image: none !important; border: 0px !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; margin: 0px !important; outline: 0px !important; overflow: visible !important; padding: 0px !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; width: auto !important; box-sizing: content-box !important; min-height: auto !important;">http://java.sun.com/jsp/jstl/fmt"%>

<html>

    <head>

        <title>Captcha</title>

    </head>

    <body>

        <form method="post">

            <img src="captcha.htm"/><input type="text"name="j_captcha_response"/><input type="submit"value="Submit"name="_finish"/>

        </form>

    </body>

</html>

· Nov 30, 2008

ferengra

Two major parts for generating a captcha image are missing from the tutorial:

Controller class responsible for image generation

importjava.awt.image.BufferedImage;

importjava.io.ByteArrayOutputStream;

 

importjavax.imageio.ImageIO;

importjavax.servlet.ServletOutputStream;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

 

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.context.i18n.LocaleContextHolder;

importorg.springframework.stereotype.Controller;

importorg.springframework.web.bind.annotation.RequestMapping;

 

importcom.octo.captcha.service.CaptchaServiceException;

importcom.octo.captcha.service.multitype.MultiTypeCaptchaService;

 

/**

 * Generates captcha image to tell whether its user is a human or a computer.

 * See http://forge.octo.com/jcaptcha/confluence/display/general/Home

 */

@Controller

publicclassCaptchaController {

 publicstaticfinalString CAPTCHA_IMAGE_FORMAT ="jpeg";

 

 @Autowired

 privateMultiTypeCaptchaService captchaService;

 

 @RequestMapping("/captcha.html")

 publicvoidshowForm(HttpServletRequest request, HttpServletResponse response)throwsException {

  byte[] captchaChallengeAsJpeg =null;

  // the output stream to render the captcha image as jpeg into

  ByteArrayOutputStream jpegOutputStream =newByteArrayOutputStream(); 

  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 = request.getSession().getId();

   BufferedImage challenge = captchaService.getImageChallengeForID(captchaId, request.getLocale()); 

 

   ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream);

  }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/"+CAPTCHA_IMAGE_FORMAT); 

 

  ServletOutputStream responseOutputStream = response.getOutputStream(); 

  responseOutputStream.write(captchaChallengeAsJpeg); 

  responseOutputStream.flush(); 

  responseOutputStream.close();

 }

}

Verifying the captcha input code

importjava.util.Date;

 

importjavax.servlet.http.HttpServletRequest;

 

importorg.slf4j.Logger;

importorg.slf4j.LoggerFactory;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.context.i18n.LocaleContextHolder;

importorg.springframework.security.providers.encoding.PasswordEncoder;

importorg.springframework.stereotype.Controller;

importorg.springframework.validation.BindingResult;

importorg.springframework.validation.Validator;

importorg.springframework.web.bind.WebDataBinder;

importorg.springframework.web.bind.annotation.InitBinder;

importorg.springframework.web.bind.annotation.ModelAttribute;

importorg.springframework.web.bind.annotation.RequestMapping;

importorg.springframework.web.bind.annotation.RequestMethod;

importorg.springframework.web.bind.annotation.SessionAttributes;

importorg.springframework.web.bind.support.SessionStatus;

 

@Controller

@RequestMapping("/registration.html")

@SessionAttributes("registrationForm")

publicclassRegistrationController {

 privatestaticLogger logger = LoggerFactory.getLogger(RegistrationController.class);

 

 publicstaticfinalString DEFAULT_ERROR_VIEW ="registration";

 publicstaticfinalString FORM_NAME ="registrationForm";

 

 @Autowired

 privateValidator validator;

 

 @Autowired

 privateMultiTypeCaptchaService captchaService;

 

 @RequestMapping(method = RequestMethod.GET)

 public@ModelAttribute(FORM_NAME) RegistrationForm showForm(HttpServletRequest request) {

  RegistrationForm form = (RegistrationForm)request.getSession().getAttribute(FORM_NAME);

  if(null== form) form =newRegistrationForm();

  returnform;

 }

 

 @RequestMapping(method = RequestMethod.POST)

 publicString processForm(

   @ModelAttribute(FORM_NAME) RegistrationForm form,

   BindingResult result, SessionStatus status, HttpServletRequest request) {

  validator.validate(form, result);

  validateCaptcha(form, result, request.getSession().getId(),"registration.captcha");

  if(result.hasErrors()) {

   returnDEFAULT_ERROR_VIEW;

  }

  ....

 }

 ....

 

 protectedvoidvalidateCaptcha(RegistrationForm registrationForm, BindingResult result, String sessionId, String errorCode) {

  // If the captcha field is already rejected

  if(null!= result.getFieldError("captcha"))return;

  booleanvalidCaptcha =false;

  try{

   validCaptcha = captchaService.validateResponseForID(sessionId, registrationForm.getCaptcha());

  }

  catch(CaptchaServiceException e) {

   //should not happen, may be thrown if the id is not valid

   logger.warn("validateCaptcha()", e);

  }

  if(!validCaptcha) {

   result.rejectValue("captcha", errorCode);

  }

 }

}

There are two bugs in the tutorial:

java.awt.Color in JDK 1.6 : The type has to be set.

<beanid="backgroundColor"class="java.awt.Color">

 <constructor-argtype="int"index="0"value="230"/> <\!-\- red -->

 <constructor-argtype="int"index="1"value="230"/> <\!-\- green -->

 <constructor-argtype="int"index="2"value="230"/> <\!-\- blue -->

</bean>

GenericManageableCaptchaService : it has 4 arguements in the constructor.

<beanid="captchaService"class="com.octo.captcha.service.multitype.GenericManageableCaptchaService">

 <constructor-argindex="0"ref="imageEngine"/>

 <constructor-argtype="int"index="1"value="180"/><!-- minGuarantedStorageDelayInSeconds -->

 <constructor-argtype="int"index="2"value="180000"/><!-- maxCaptchaStoreSize -->

 <constructor-argtype="int"index="3"value="75000"/><!-- captchaStoreLoadBeforeGarbageCollection -->

</bean>

Afterwards the captcha image can be inserted in the JSP file:

<s:messagevar="captchaTitle"code="captcha.title"/>

<imgsrc="captcha.html"title="${captchaTitle}"alt="${captchaTitle}"/>

· Apr 23, 2009

Naz

Hello,

I am trying to integrate JCaptcha step by step in my application which uses Spring. I have added this line to my url-mapping.xml.

<bean class="com.octo.captcha.service.image.DefaultManageableImageCaptchaService" id="imageCaptchaService"/>

but when starting the app I get following error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'imageCaptchaService' defined in ServletContext resource/WEB-INF/conf/spring/web/url-mapping.xml: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class com.octo.captcha.service.image.DefaultManageableImageCaptchaService: Constructor threw exception; nested exception is java.lang.NoSuchMethodError: com.jhlabs.image.WaterFilter.setAmplitude(D)V

I am using jcaptch1.0.

Any help is appreciated.

Thanks,
N

· Jan 18, 2010

Naz

basically in details it says:

Caused by: java.lang.NoSuchMethodError: com.jhlabs.image.WaterFilter.setAmplitude(D)V

· Jan 18, 2010

Naz

Using JCaptcha2 it says

org.springframework.beans.factory.CannotLoadBeanClassException: Error loading classcom.octo.captcha.engine.image.gimpy.SimpleListImageCaptchaEngine for bean with name 'captchaEngine' defined in ServletContext resource /WEB-INF/conf/spring/web/url-mapping.xml: problem with class file or dependent class; nested exception is java.lang.UnsupportedClassVersionError: Bad version number in .class file (unable to load class com.octo.captcha.engine.image.gimpy.SimpleListImageCaptchaEngine)

My JDK is 1.5!!

It is driving me crazy 

 Jan 18, 2010

ferengra

My guess is that you don't have the imaging-01012005.jar, which is required for catcha.jar.

<dependency>

 <groupId>com.jhlabs</groupId>

 <artifactId>imaging</artifactId>

 <version>01012005</version>

</dependency>

It can be taken from http://maven.jahia.org/maven2/com/jhlabs/imaging/01012005/


7Simple Servlet Integration documentation

Description

This integration module provides the shortest way to integrate JCaptcha to your web application.
This module is available since jcaptcha 2.0

This integration module provides the new default captcha configuration :

All you need to do is add the jcaptcha jar to your project, make a reference to the SimpleImageCaptchaServlet in your web.xml and then use the servlet session id to validate what the user submits on your form against the captcha service.

Set up

· Add the jcaptcha jar file into the WEB-INF/lib directory of your .war file

· If your app or server do not already have commons-logging and commons-collection into the WEB-INF/lib directory of your .war

· Put the reference in your web.xml (checking that the url-pattern path matches up with what you put in your html fragment above):

<servlet>

        <servlet-name>jcaptcha</servlet-name>

        <servlet-class>com.octo.captcha.module.servlet.image.SimpleImageCaptchaServlet</servlet-class>

</servlet>

<servlet-mapping>

        <servlet-name>jcaptcha</servlet-name>

        <url-pattern>/jcaptcha.jpg</url-pattern>

</servlet-mapping>

· Add the folowing image tag to the form you want to protect, this call will asks the SimpleImageCaptchaServlet to generate a fresh new captcha

<formaction="submit.action">

...

    <imgsrc="jcaptcha.jpg"/> <inputtype="text"name="jcaptcha"value=""/>

...

</form>

· In your code that manages the submit action add the following code fragment to validate the user input

String userCaptchaResponse = request.getParameter("jcaptcha");

booleancaptchaPassed = SimpleImageCaptchaServlet.validateResponse(request, userCaptchaResponse);

if(captchaPassed){

// proceed to submit action

}else{

// return error to user

}

And that's it!

Sample Web App

· see the attached sample web app (warning, this war contains commons-logging and commons-collections)

Jcaptcha 2.0 jars

· jcaptcha-api-1.0.jar

· jcaptcha-2.0-alpha-1-SNAPSHOT.jar

· jcaptcha-integration-simple-servlet-2.0-alpha-1-SNAPSHOT.jar

· filters-2.0.235.jar






原创粉丝点击