标签:
本文将使用Jcaptcha实现校验码验证,并演示在Spring/SpringMVC环境下的使用方法。
1. maven依赖
<dependency>
<groupId>com.octo.captcha</groupId>
<artifactId>jcaptcha-all</artifactId>
<version>1.0-RC6</version>
<exclusions>
<exclusion>
<groupId>quartz</groupId>
<artifactId>quartz</artifactId>
</exclusion>
<exclusion>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</exclusion>
<exclusion>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
</exclusion>
<exclusion>
<groupId>hsqldb</groupId>
<artifactId>hsqldb</artifactId>
</exclusion>
<exclusion>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</exclusion>
<exclusion>
<groupId>concurrent</groupId>
<artifactId>concurrent</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xmlParserAPIs</artifactId>
</exclusion>
</exclusions>
</dependency>
注:请按需对需要排除的依赖进行增减
2. 需要将Jcaptcha的Bean加入Spring管理,故新增Spring-Jcaptcha的配置文件。web.xml中
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:applicationContext.xml
classpath*:applicationContext-captcha.xml
</param-value>
</context-param>
3. applicationContext-captcha.xml的内容
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-lazy-init="true">
<bean id="captchaService" class="com.octo.captcha.service.multitype.GenericManageableCaptchaService">
<constructor-arg index="0" ref="imageEngine" />
<constructor-arg type="int" index="1" value="180" />
<constructor-arg type="int" index="2" value="100000" />
</bean>
<bean id="imageEngine" class="com.octo.captcha.engine.GenericCaptchaEngine">
<constructor-arg index="0">
<list>
<ref bean="captchaFactory" />
</list>
</constructor-arg>
</bean>
<bean id="captchaFactory" class="com.octo.captcha.image.gimpy.GimpyFactory">
<constructor-arg>
<ref bean="wordgen" />
</constructor-arg>
<constructor-arg>
<ref bean="wordtoimage" />
</constructor-arg>
</bean>
<bean id="wordgen" class="com.octo.captcha.component.word.wordgenerator.RandomWordGenerator">
<!--可选字符-->
<constructor-arg>
<value>
0123456789abcdefghijklmnopqrstuvwxyz
</value>
</constructor-arg>
</bean>
<bean id="wordtoimage" class="com.octo.captcha.component.image.wordtoimage.ComposedWordToImage">
<constructor-arg index="0">
<ref bean="fontGenRandom" />
</constructor-arg>
<constructor-arg index="1">
<ref bean="backGenUni" />
</constructor-arg>
<constructor-arg index="2">
<ref bean="decoratedPaster" />
</constructor-arg>
</bean>
<bean id="fontGenRandom" class="com.octo.captcha.component.image.fontgenerator.RandomFontGenerator">
<!--最小字体-->
<constructor-arg index="0">
<value>20</value>