博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用jcaptcha插件生成验证码
阅读量:6284 次
发布时间:2019-06-22

本文共 5595 字,大约阅读时间需要 18 分钟。

1.从官网下载插件。将对应jar包导入到lib文件夹下
图片
2.创建一个CaptchaServiceSingleton类用来获取jcaptcha自己实现的默认验证码生成器对象DefaultManageableImageCaptchaService(使用单例模式)。
package com.xhc.jcaptcha;import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;import com.octo.captcha.service.image.ImageCaptchaService;public class CaptchaServiceSingleton {  private static ImageCaptchaService instance = new DefaultManageableImageCaptchaService();      public static ImageCaptchaService getInstance(){         return instance;     }}
3.创建处理验证码生成的servlet
package com.xhc.jcaptcha;import java.awt.image.BufferedImage;import java.awt.image.Raster;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 com.octo.captcha.service.CaptchaServiceException;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageEncoder;public class ImageCaptchaServlet extends HttpServlet { public void destroy() {  super.destroy(); } public 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 = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);                     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(); } public void init(ServletConfig servletConfig) throws ServletException {  super.init(servletConfig); }}
若导入这两个类时报错
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
原因:Eclipse默认把这些受訪问限制的API设成了ERROR。

仅仅要把Windows-Preferences-Java-Complicer-Errors/Warnings里面的Deprecated  and restricted API中的Forbidden references(access rules)选为Warning就能够编译通过。

4.创建用来做验证的servlet
package com.xhc.jcaptcha;import java.io.IOException;import java.io.PrintWriter;import java.net.HttpRetryException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.octo.captcha.service.CaptchaServiceException;public class ValidationServlet extends HttpServlet { public void destroy() {  super.destroy(); // Just puts "destroy" string in log  // Put your code here } public 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        httpServletResponse.setContentType("text/html;charset=utf-8");       PrintWriter wt=httpServletResponse.getWriter();               try {             isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(captchaId,                     response);             if(isResponseCorrect){              wt.write("验证码输入成功");             }else{              wt.write("验证码输入失败");             }         } catch (CaptchaServiceException e) {              //should not happen, may be thrown if the id is not valid         } }  public void init() throws ServletException { }}
5.配置web.xml
 
ImageCaptchaServlet
com.xhc.jcaptcha.ImageCaptchaServlet
0
ValidationServlet
com.xhc.jcaptcha.ValidationServlet
ImageCaptchaServlet
/servlet/ImageCaptchaServlet
ValidationServlet
/servlet/ValidationServlet
6.jsp页面
 
你可能感兴趣的文章
《Exchange Server 2010 SP1/SP2管理实践》——2.4 部署外部网络环境
查看>>
Firefox 是 Pwn2own 2014 上攻陷次数最多的浏览器
查看>>
阿里感悟(十八)- 应届生Review
查看>>
《计算广告:互联网商业变现的市场与技术》一第一部分 在线广告市场与背景...
查看>>
话说模式匹配(5) for表达式中的模式匹配
查看>>
《锋利的SQL(第2版)》——1.7 常用函数
查看>>
《Arduino家居安全系统构建实战》——1.5 介绍用于机器学习的F
查看>>
jquery中hover()的用法。简单粗暴
查看>>
线程管理(六)等待线程的终结
查看>>
spring boot集成mongodb最简单版
查看>>
DELL EqualLogic PS存储数据恢复全过程整理
查看>>
《Node.js入门经典》一2.3 安装模块
查看>>
《Java 开发从入门到精通》—— 2.5 技术解惑
查看>>
Linux 性能诊断 perf使用指南
查看>>
实操分享:看看小白我如何第一次搭建阿里云windows服务器(Tomcat+Mysql)
查看>>
Sphinx 配置文件说明
查看>>
数据结构实践——顺序表应用
查看>>
python2.7 之centos7 安装 pip, Scrapy
查看>>
机智云开源框架初始化顺序
查看>>
Spark修炼之道(进阶篇)——Spark入门到精通:第五节 Spark编程模型(二)
查看>>