原文->http://wwwzhouhui.iteye.com/blog/410935
现在项目中用SPRING 比较多所以整合了一下。其中的部分代码是参考一个jeecms项目的,讲其中的jcaptcha验证码这块剥离出来。
项目在上篇基础上编写的,部分代码是上篇中的代码(偷懒了)
1.用到得JAR
commons-logging.jar,jcaptcha-all-1.0-RC6.jar,spring-beans-2.5.6.jar
spring-context-2.5.6.jar,spring-core-2.5.6.jar,spring-web-2.5.6.jar
2.applicationContext.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"
- xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
- >
- <!--验证码生成器-->
- <bean id="imageCaptchaService" class="com.spring.CaptchaService">
- <constructor-arg type="com.octo.captcha.service.captchastore.CaptchaStore" index="0">
- <ref bean="fastHashMapCaptchaStore"/>
- </constructor-arg>
- <!--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"/>
- <!--you can define more than one captcha engine here -->
- <bean id="captchaEngineEx" class="com.spring.CaptchaEngineEx"/>
- </beans>
3. web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.4"
- xmlns="http://java.sun.com/xml/ns/j2ee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
- http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>
- classpath:applicationContext.xml
- </param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <!--
- <servlet>
- <servlet-name>jcaptcha</servlet-name>
- <servlet-class>com.code.ImageCaptchaServlet</servlet-class>
- <load-on-startup>0</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>jcaptcha</servlet-name>
- <url-pattern>/jcaptcha</url-pattern>
- </servlet-mapping>
- -->
- <servlet>
- <servlet-name>jcaptcha2</servlet-name>
- <servlet-class>com.spring.ImageCaptchaServlet</servlet-class>
- <load-on-startup>0</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>jcaptcha2</servlet-name>
- <url-pattern>/jcaptcha</url-pattern>
- </servlet-mapping>
- <!--
- <servlet>
- <servlet-name>checkjcaptcha</servlet-name>
- <servlet-class>com.code.ValidationServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>checkjcaptcha</servlet-name>
- <url-pattern>/validateAction</url-pattern>
- </servlet-mapping>
- -->
- <servlet>
- <servlet-name>checkjcaptcha2</servlet-name>
- <servlet-class>com.spring.ValidationServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>checkjcaptcha2</servlet-name>
- <url-pattern>/validateAction</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
4.java 代码
自定义生成代码部分
CaptchaEngineEx.java
- package com.spring;
- 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;
- /***********************************************************************
- *
- * CaptchaEngineEx.java
- * @copyright Copyright: 2009-2012
- * @creator 周辉<br/>
- * @create-time Jun 18, 2009 2:41:12 PM
- * @revision $Id: *
- ***********************************************************************/
- 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
- // abcdefghijklmnopqrstuvwxyz
- WordGenerator wordGenerator = new RandomWordGenerator("0123456789");
- // 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));
- }
- }
生成图片的servlet
ImageCaptchaServlet.JAVA
- package com.spring;
- import java.awt.image.BufferedImage;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- 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 org.springframework.web.context.WebApplicationContext;
- import org.springframework.web.context.support.WebApplicationContextUtils;
- 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;
- /***********************************************************************
- *
- * ImageCaptchaServlet.java
- * @copyright Copyright: 2009-2012
- * @creator 周辉<br/>
- * @create-time Jun 18, 2009 2:44:15 PM
- * @revision $Id: *
- ***********************************************************************/
- @SuppressWarnings("serial")
- public class ImageCaptchaServlet extends HttpServlet {
- private ImageCaptchaService imageCaptchaService;
- private String beanName = "imageCaptchaService";
- public void init(ServletConfig servletConfig) throws ServletException {
- super.init(servletConfig);
- WebApplicationContext wac = WebApplicationContextUtils
- .getRequiredWebApplicationContext(servletConfig
- .getServletContext());
- imageCaptchaService = (ImageCaptchaService) wac.getBean(beanName,
- ImageCaptchaService.class);
- }
- 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 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();
- }
- }
验证的单列类 CaptchaService.java
- package com.spring;
- import com.octo.captcha.engine.CaptchaEngine;
- import com.octo.captcha.service.captchastore.CaptchaStore;
- import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;
- /***********************************************************************
- *
- * CaptchaService.java
- * @copyright Copyright: 2009-2012
- * @creator 周辉<br/>
- * @create-time Jun 18, 2009 2:42:53 PM
- * @revision $Id: *
- ***********************************************************************/
- public class CaptchaService extends DefaultManageableImageCaptchaService {
- public CaptchaService() {
- super();
- }
- public CaptchaService(int minSeconds, int maxStoreSize, int loadBefore) {
- super(minSeconds, maxStoreSize, loadBefore);
- }
- public CaptchaService(CaptchaStore captchaStore,
- CaptchaEngine captchaEngine, int minSeconds, int maxStoreSize,
- int loadBefore) {
- super(captchaStore, captchaEngine, minSeconds, maxStoreSize, loadBefore);
- }
- public Boolean validateResponseForID(String ID, Object response) {
- Boolean isHuman;
- try {
- isHuman = super.validateResponseForID(ID, response);
- } catch (Exception e) {
- isHuman = false;
- }
- return isHuman;
- }
- }
最后测试验证的类
ValidationServlet.java
- package com.spring;
- import java.io.IOException;
- import javax.servlet.ServletConfig;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.web.context.WebApplicationContext;
- import org.springframework.web.context.support.WebApplicationContextUtils;
- import com.octo.captcha.service.CaptchaServiceException;
- import com.octo.captcha.service.image.ImageCaptchaService;
- /***********************************************************************
- *
- * ValidationServlet.java
- * @copyright Copyright: 2009-2012
- * @creator 周辉<br/>
- * @create-time Jun 18, 2009 3:16:50 PM
- * @revision $Id: *
- ***********************************************************************/
- public class ValidationServlet extends HttpServlet {
- private ImageCaptchaService imageCaptchaService;
- private String beanName = "imageCaptchaService";
- public void init(ServletConfig servletConfig) throws ServletException {
- super.init(servletConfig);
- WebApplicationContext wac = WebApplicationContextUtils
- .getRequiredWebApplicationContext(servletConfig
- .getServletContext());
- imageCaptchaService = (ImageCaptchaService) wac.getBean(beanName,
- ImageCaptchaService.class);
- }
- protected void doGet(HttpServletRequest httpServletRequest,
- HttpServletResponse httpServletResponse) throws ServletException,
- IOException {
- Boolean isResponseCorrect = Boolean.FALSE;
- //remenber that we need an id to validate!
- String captchaId = httpServletRequest.getSession().getId();
- //retrieve the response
- String response = httpServletRequest.getParameter("j_captcha_response");
- // Call the Service method
- try {
- isResponseCorrect=imageCaptchaService.validateResponseForID(captchaId, response);
- } catch (CaptchaServiceException e) {
- //should not happen, may be thrown if the id is not valid
- }
- System.out.println(isResponseCorrect);
- // httpServletResponse.encodeUrl("sucess.html");
- if(isResponseCorrect.booleanValue()){
- httpServletResponse.sendRedirect("success.html");
- }
- else {
- httpServletResponse.sendRedirect("failture.html");
- }
- }
- }
5 页面HTML
login2.html
- <html>
- <head>
- <title>MyHtml.html</title>
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="this is my page">
- <meta http-equiv="content-type" content="text/html; charset=UTF-8">
- <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
- </head>
- <body>
- <form name="f1" id="f1" action="/jcaptcha/validateAction" method="get">
- <table border="0">
- <tr>
- <td>验证码:</td>
- <td><img src="jcaptcha"><input type='text' name='j_captcha_response' value=''></td>
- </tr>
- <tr>
- <td colspan="2" align="center"><input type="submit"></td>
- </tr>
- </table>
- </form>
- </body>
- </html>
6 最后调用成功失败的页面success.html failture.html(略)
最后发布程序,启动TOMCAT 输入
http://localhost:8081/jcaptcha/login2.html
看到生成验证码了
相关推荐
**jcaptcha验证码程序详解** 验证码(CAPTCHA)是一种防止机器自动操作的安全机制,它通过让用户识别并输入图片中的字符来验证用户是否为真人。在Java开发中,`jcaptcha`是一个广泛使用的开源库,用于生成复杂的...
Java验证码组件Jcaptcha是用于生成安全、动态的图像验证码的工具,主要目的是为了防止自动化的机器人或恶意软件在...通过学习和理解Jcaptcha的原理及使用方式,开发者可以更好地应对网络安全挑战,提升应用的防护能力。
总之,`jcaptcha-sample` 是一个很好的学习资源,它让你了解如何在 Java 应用中集成和使用验证码技术,以提高应用的安全性。通过研究这个项目,你可以掌握验证码的原理,并能够根据具体需求调整和优化验证码的生成与...
**JCaptcha开源验证码组件详解** 验证码(CAPTCHA)是一种用于防止自动机器人滥用服务的技术,它通过让用户解决人类容易但机器难以解决...学习和掌握JCaptcha的使用,能够帮助开发者更好地保护Web应用免受自动化攻击。
本篇文章将详细讲解两个流行的验证码开源组件——Jcaptcha和Kaptcha,它们为开发者提供了便捷的方式来生成和验证图像验证码。 首先,Jcaptcha(Just Another CAPTCHA Toolkit)是一个强大的Java验证码框架,它提供...
3. **视图资源**:JSP页面或FreeMarker模板,用于展示带有JCaptcha验证码的表单。这些文件通常包含一个图像标签,显示由JCaptcha生成的验证码图片,以及一个文本框供用户输入验证码。 4. **JCaptcha库**:可能包含...
**标题:“jcaptcha学习spring整合”** 在IT领域,验证码(CAPTCHA)是防止恶意自动化程序(如机器人)滥用服务的重要安全措施。Jcaptcha(Java CAPTCHA)是一个开源的Java库,专门用于生成复杂的验证码图像,以...
Struts验证码插件JCaptcha...通过深入学习和实践JCaptcha4Struts2,开发者可以构建更加安全、可靠的用户验证机制,有效防止恶意攻击,保护用户数据的安全。同时,掌握这个插件的使用也对提升Java后端开发能力大有裨益。
通过以上步骤,开发者可以轻松地在Struts2应用中集成JCaptcha验证码功能,提高系统安全性和用户体验。这个实例源码是一个很好的学习资源,可以帮助开发者理解如何将验证码技术应用于实际项目中。
jcaptcha验证码** jcaptcha是一个Java实现的验证码库,主要用于防止恶意自动化的机器人进行非法操作。在这个项目中,jcaptcha生成的图形验证码用于注册和登录环节,增加了用户验证,确保提交信息的是真实的人而非...
通过学习JCAPTCHA的源码,开发者不仅可以了解验证码系统的基本设计原则,还能获取到在实际项目中实现安全验证功能的宝贵经验。对于希望提升网络安全技能或进行验证码相关开发的人员来说,这是一份非常有价值的参考...
总结来说,"jcaptcha4struts2-demo-2.0.1.zip"提供了一个学习和实践Jcaptcha4Struts2验证码组件的实例。通过这个DEMO,开发者可以了解到如何在Struts2环境中集成和使用验证码,从而提升Web应用的安全性。无论是初学...
Java验证码生成库JCaptcha是一个广泛使用的开源库,用于在Java应用程序中创建安全的、难以破解的验证码。...通过学习和使用JCaptcha,开发人员可以为他们的应用程序添加一层额外的安全保护,防止自动化的恶意行为。
通过这些文档,开发者可以学习如何配置jCaptcha,如何自定义验证码的外观,以及如何处理验证结果。 fisheyebackgrounds和gimpybackgrounds两个目录可能存储了jCaptcha的背景图片模板。jCaptcha支持各种复杂的背景...
标题“jcaptchaDemo”指的是一个基于Java的项目,它展示了如何使用jcaptcha(Just Another CAPTCHA)库来创建和验证验证码。jcaptcha是一个开源的验证码解决方案,旨在提供一种有效的方法来防止自动化的机器人程序...
7. **技术选型**:在Java Web环境中,验证码的实现可以使用纯Java代码,也可以借助第三方库,如JCaptcha或滑动验证码库如SlidCaptcha。这些库提供了更高级的功能,如自定义样式和更好的抗机器学习算法。 8. **用户...
在Java开发环境中,`JCaptcha`是一个非常强大的验证码生成库,它允许开发者轻松地在项目中集成安全且可自定义的验证码功能。本文将深入探讨`JCaptcha`的特性、工作原理以及如何将其应用到实际项目中。 首先,`...
这是一个基于acegi的jcaptcha的验证码例子,希望对正在学习的大家有所帮助
3. **颜色与字体的多样化**:Jcaptcha支持多种颜色和字体组合,进一步增加了验证码的复杂性,使得机器学习模型难以建立通用的识别模型。 4. **可扩展性**:Jcaptcha设计为模块化,开发者可以自定义生成器、扭曲器、...
【资源说明】 1、该资源包括项目的全部源码,下载可以直接使用! 2、本项目适合作为计算机、数学、电子信息等专业的课程设计...基于SSM实现的注册登录系统源码+项目说明(验证码使用jcaptcha,发送邮件使用JEmail).zip