用开源组件jcaptcha做jsp彩色验证码
key words: jsp验证码 jcaptcha

原文参考 这里

安装

Add jcaptcha-all.jar (provided in bin-distribution) and ehcache.jar (not provided see ehcache site) to your application class path, ie in you WEB-INF/lib folder.

实例一个jcaptcha服务,注意,必须是单例模式的

import com.octo.captcha.service.image.ImageCaptchaService;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;

public class CaptchaServiceSingleton {
    
    private static ImageCaptchaService instance = new DefaultManageableImageCaptchaService();
    
    public static ImageCaptchaService getInstance(){
        return instance;
    }
}

注:以上是默认的一个实现,下面是其他更多的实现

  • SimpleListSoundCaptchaEngine   //还可以用声音,真爽哦
  • SpellerSoundCaptchaEngine
  • SpellerSoundCaptchaEngine
  • DefaultGimpyEngineCaptcha
  • BaffleListGimpyEngineCaptcha
  • BasicListGimpyEngineCaptcha
  • DeformedBaffleListGimpyEngineCaptcha
  • DoubleRandomListGimpyEngineCaptcha
  • SimpleListImageCaptchaEngineCaptcha
  • SimpleFishEyeEngineCaptcha

具体请参考官方说明

编写一个产生图片的servlet

import com.octo.captcha.service.CaptchaServiceException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

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;

public class ImageCaptchaServlet extends HttpServlet {

public void init(ServletConfig servletConfig) throws ServletException {

super.init(servletConfig);

}

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 =
                    CaptchaServiceSingleton.getInstance().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();
    }
}

为servlet修改web.xml配置文件

<servlet>
        <servlet-name>jcaptcha</servlet-name>
        <servlet-class>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>

编写你的客户端的展示

<img src="jcaptcha">
<input type='text' name='j_captcha_response' value=''>

上面的src="jcaptcha"  就是调用了上面的servlet,text里是用户填写的确认验证码

后台逻辑验证

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 = CaptchaServiceSingleton.getInstance().validateResponseForID(captchaId,
                        response);
            } catch (CaptchaServiceException e) {
                 //should not happen, may be thrown if the id is not valid 
            }

OK,大功告成了.

用开源组件jcaptcha做jsp彩色验证码相关推荐

  1. JSP实例-彩色验证码

    image.java用于产生彩色验证码,其代码如下: package test; import java.awt.Color; import java.awt.Font; import java.aw ...

  2. 英文.数字和中文混合的彩色验证码【JSP】

    一.编写生成英文,数字和中文混合的彩色验证码的Servlet实现类 (1)创建名称为PictureCheckCode.java的Servlet. public class PictureCheckCo ...

  3. java做jsp问题_java/jsp中 中文问题详解

    java/jsp中 中文问题详解 更新时间:2006年10月13日 00:00:00   作者: 预备知识: 1.字节和unicode Java内核是unicode的,就连class文件也是,但是很多 ...

  4. 如何用开源组件“攒”出一个大数据建模平台?

    写在前面:博主是一只经过实战开发历练后投身培训事业的"小山猪",昵称取自动画片<狮子王>中的"彭彭",总是以乐观.积极的心态对待周边的事物.本人的技 ...

  5. 开源组件websocket-sharp中基于webapi的httpserver使用体验

    一.背景 因为需要做金蝶ERP的二次开发,金蝶ERP的开放性真是不错,但是二次开发金蝶一般使用引用BOS.dll的方式,这个dll对newtonsoft.json.dll这个库是强引用,必须要用4.0 ...

  6. .net 开源组件推荐 之 StackExchange

    原文:.net 开源组件推荐 之 StackExchange 已经两年没更新过博客了!!! StackExchange,地址:https://github.com/StackExchange,开源的这 ...

  7. 用开源组件构建属于你的 PHP 框架

    为什么要构建自己的 PHP 框架? 现在的 PHP 框架很多,当然不止 PHP ,即使是其他编程语言也有很多框架,这篇文章讲 PHP 框架构建是因为我对 PHP 的生态最为熟悉,但这个方法同样也适用于 ...

  8. Winform中使用EasyPlayer-RTSP-Win开源组件实现播放RTSP视频流

    场景 开源RTMP组件EasyPusher-Android+EasyDarwin实现APP推流给RTSP流媒体服务器: 开源RTMP组件EasyPusher-Android+EasyDarwin实现A ...

  9. idea本地跑如何看gc日志_牛逼了!用 IDEA 扒出了开源组件导致FGC的原因

    某天上午收到最近发布的一个服务频繁FGC的告警,这个服务只是给公司内部相关人员使用的,并非给互联网用户提供服务的系统.而且功能也比较简单,就是查看一些统计信息.报表数据.数据导出Excel等,访问量非 ...

最新文章

  1. 进程状态控制-进程的阻塞和唤醒
  2. C++_STL——array(C++11)
  3. 《大话设计模式》第29章-OOTV杯超级模式大赛—模式总结(四)
  4. centos7.6基础
  5. WM_CTLCOLOR消息
  6. 关于Verilog中begin···end语句执行顺序
  7. 如何用Pygame写游戏(十三)
  8. eclipse ide for c/c++_大众CC新款开启新的人生 辉煌报价钜惠 _车讯网chexun.com
  9. 横向扩展 纵向扩展 数据库_扩展数据库–减少扩展的艺术
  10. linux设置开机启动 服务不支持chkconfig解决方法脚本
  11. 可任意自定义的UITableViewCell(转)
  12. [LevelDB] 编译和使用
  13. Hadoop数据开发笔试题(一)
  14. mysql error 1213_webgame中Mysql Deadlock ERROR 1213 (40001)错误的排查历程
  15. Chrome浏览器打开微信页面
  16. Hyperledger Fabric 管理链码 peer lifecycle chaincode 指令使用
  17. 上门洗车小程序/APP功能介绍
  18. SNF开发平台-SNF.CodeGenerator-升级生成BS页面代码-支持视图-数据库配置-快速开发者的利器...
  19. 常见多变量/多元统计分析方法分类图
  20. VS Code 下载和安装教程

热门文章

  1. [转] Spring XML配置十二个最佳实践
  2. mybatis基础,mybatis核心配置文件properties元素
  3. Spring的事务管理
  4. 使用history.back()出现警告: 网页已过期的解决办法
  5. Git小结---So far.......
  6. [转]AAuto编程语言官方站 网站服务条款
  7. DNS 服务器 4013警告信息的解决
  8. 【廖雪峰官方网站/Java教程】多线程(3)
  9. 证明$A^TAX = A^Tb$有公共解
  10. 【尚未完成,不建议参考】马氏距离,汉明距离