- 浏览: 115639 次
- 性别:
- 来自: 广州
文章分类
最新评论
-
Kevin_jiang2011:
能直接在,代码里面配置吗?
Spring+CXF配置HTTP代理访问Internet -
xbiji:
不能用啊!!!!!!!!!!!!!!!!!!!!!!1
JQuery获取页面高度,页面宽度,窗口高度,窗口宽度 -
ben_liang:
# <http-conf:proxyAuthoriza ...
Spring+CXF配置HTTP代理访问Internet -
navy0168:
package com;import java.io. ...
解压缩
转自:http://flattop.iteye.com/blog/146135
1、从jcaptcha官方网站下载jcaptcha的发行包,并将其发行包中的jar文件考贝到本地项目WEB-INF目录下的lib目录中。
官方网址http://jcaptcha.sourceforge.net/
2、在web.xml文件中配置
Java代码
<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>
<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中的配置
Java代码
<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,自己加去吧
<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 类
Java代码
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));
}
}
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 类
Java代码
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));
}
}
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 类
Java代码
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();
}
}
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 类
Java代码
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;
}
}
1、从jcaptcha官方网站下载jcaptcha的发行包,并将其发行包中的jar文件考贝到本地项目WEB-INF目录下的lib目录中。
官方网址http://jcaptcha.sourceforge.net/
2、在web.xml文件中配置
Java代码
<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>
<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中的配置
Java代码
<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,自己加去吧
<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 类
Java代码
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));
}
}
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 类
Java代码
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));
}
}
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 类
Java代码
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();
}
}
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 类
Java代码
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;
}
}
发表评论
-
Java网站
2010-12-11 02:15 667转自:http://txxm.iteye.com/blog/5 ... -
一些反射常用的工具类
2010-09-17 13:59 1630拷贝属性: 1.org.apache.commons.bean ... -
Java安全管理器
2010-08-17 11:00 1599转:http://yuanyong.iteye.com ... -
jenlp110 的 一道面试题
2010-07-28 14:01 842转自:http://www.iteye.com/topic/5 ... -
Web前端开发性能优化
2010-07-28 11:01 925参考资料:http://developer.yahoo.com ... -
比较java写text文件的性能
2010-07-20 11:13 979转自:http://hi.baidu.com/shmily_s ... -
dom4j读取xml:转http://shaqiang32.javaeye.com/blog/246539
2010-06-25 16:52 865SAXReader reader = new SAXRea ... -
反射-调用有参数和无参数的方法
2010-06-19 13:48 9093package com.cn.service; /** ... -
excel导出2
2010-02-05 12:37 860使用POI生成Excel文件,可以自动调整excel列宽等 ... -
多线程-条件变量: 转自:http://huanyue.javaeye.com/blog/560975
2010-01-14 17:56 657条件变量是Java5线程中很重要的一个概念,顾名思义,条件变量 ... -
多线程交互-障碍器 转自:http://huanyue.javaeye.com/blog/560978
2010-01-14 17:24 762Java5中,添加了障碍器类,为了适应一种新的设计需求,比如一 ... -
线程交互-转自:http://huanyue.javaeye.com/blog/560904
2010-01-14 17:13 868一、线程交互的基础知识 SCJP所要求的线程交互知识点需要 ... -
递归计算向非递归计算转换模板-转自http://mingliangfeng.javaeye.com/blog/201084
2010-01-14 13:36 846最近由于工作上的需要,研究了一下递归计算向非递归计算的转换问题 ... -
excel 导出
2010-01-11 15:06 1106public static InputStream Expor ...
相关推荐
今天专门给大家来聊聊验证码的问题,一般的情况下遇到验证码我们可以都可以找开发去帮忙解决,关闭验证码,或者给一个万能的验证码!那么如果开发不提供帮助的话,我们自己有没有办法来处理这些验证码的问题呢?答案...
好东西好西欧年各地验证码验证码验证码验证码
形状识别,验证码,二值化,形状识别,验证码,二值化,形状识别,验证码,二值化,形状识别,验证码,二值化,形状识别,验证码,二值化,形状识别,验证码,二值化,形状识别,验证码,二值化,形状识别,验证码,...
DraggedCaptchaApplication为启动滑动验证码demo。 2.运行环境支持 2.1 JDK1.8 2.2. MAVEN-3.3 2.3. spring-boot-2.1.17.RELEASE 2.4. Redis 3. 核心技术要点 3.1.JAVA掌握AWT的BufferedImage、Graphics2D、...
获取验证码图片,不是识别验证码!获取验证码图片,不是识别验证码!获取验证码图片,不是识别验证码!获取验证码图片,不是识别验证码!获取验证码图片,不是识别验证码!获取验证码图片,不是识别验证码!获取验证码图片,不是...
1.以下验证码例子采用的是先获取手机号文字验证码,如果文字验证码收不到,将采用语音播放验证码的形式,两种形式的结合,基本避免个别手机号收不到的问题,从而是验证码的成功率接近100%,有效的避免客户的流失。...
验证码
验证码的三种做法验证码的三种做法验证码的三种做法验证码的三种做法验证码的三种做法验证码的三种做法验证码的三种做法验证码的三种做法验证码的三种做法验证码的三种做法验证码的三种做法验证码的三种做法验证码的...
提供一种可管理的,可配置的,集中式的验证码管理方案, 该方案是个人在做一套多功能投票系统时的一项小功能。 1、可以集中管理网站中的多种验证码 2、通过扩展可以实现动态切换验证码 3、可自行开发验证码,然后...
整个html打开可以看到效果,不包含验证码背景图片,自己找一个命名为code.jpg就有背景了,js验证码比jsp...这个程序既可以直接验证,也可以点击验证码刷新一个新的验证码(当原来的验证码看不清楚的时候),再验证
看很多人都在找asp 验证码 asp 随机验证 我收集了四个非常优秀的ASP随机验证码,非常好用,分别为: Asp纯数字随机验证码程序 (5.98 kb) Asp数字及字母组合验证码程序(5.98 kb) Asp纯字母验证码程序.zip (5.98 kb ...
project验证码project验证码project验证码project验证码
一个低调的行为验证码 [滑块验证码、点选验证码、行为验证码、旋转验证码, 滑动验证码].zip
java验证码识别示例
首先贴一张验证码上来做案例: 第一步先通过二值化处理把干扰线去掉: from PIL import Image # 二值化处理 def two_value(): for i in range(1,5): # 打开文件夹中的图片 image=Image.open('./Img/'+str(i)+'....
js验证码插件,简单易用,图片验证码,前端网站开发可用,附demo
本程序是采用Windows GDI+技术模拟Web上的验证码生成而设计的一款Windows版验证码随机生成程序,利用GDI+图形图像处理技术,可随机生成强验证码(即汉字验证码)或弱验证码(即数字和字母组合验证码),支持验证码的...
csdn上三种java验证码生成方法,以及谷歌开源验证码,总共四种验证码生成集合。将生成的四个验证图片放在一个页面上以供比对,全部可以运行。 四种方法分别为: 1. 数字、字母、汉字混合验证码,叠影(给力)、扭曲 ...
java实现滑动验证码
VC++验证码生成Base64验证码png图片程序,如何使用VC++生成验证码图片,输出Base64图片给网页调用