jcaptcha和kaptcha验证码使用入门
一、jcaptcha验证码使用
jcaptcha使用默认样式生成的验证码比较难以识别,所以需要自定义验证码的样式,包括,背景色、背景大小、字体、字体大小、生成的字符数等。相对与kaptcha比较复杂。
1.1、纯代码实现jcaptcha验证码
1、首先创建一个javaWeb工程添加jcaptcha包和它所依赖的包,添加完成后:
2、创建一个jcaptcha单例的Service类,这里是设置验证码样式的关键部分,代码如下:
package cn.v5cn.jcaptchatest.custom; import java.awt.Font; import com.octo.captcha.CaptchaFactory;import com.octo.captcha.component.image.backgroundgenerator.UniColorBackgroundGenerator;import com.octo.captcha.component.image.color.RandomRangeColorGenerator;import com.octo.captcha.component.image.fontgenerator.RandomFontGenerator;import com.octo.captcha.component.image.textpaster.RandomTextPaster;import com.octo.captcha.component.image.wordtoimage.ComposedWordToImage;import com.octo.captcha.component.word.FileDictionary;import com.octo.captcha.component.word.wordgenerator.ComposeDictionaryWordGenerator;import com.octo.captcha.engine.GenericCaptchaEngine;import com.octo.captcha.image.gimpy.GimpyFactory;import com.octo.captcha.service.image.ImageCaptchaService;import com.octo.captcha.service.multitype.GenericManageableCaptchaService; public class CaptchaServiceSingleton { private static ImageCaptchaService service = null; public static ImageCaptchaService getService(){ if(service == null) service = generatorCaptchaService(); return service; } /** * 根据SpringBean的配置文件编写的代码实现 * */ public static ImageCaptchaService generatorCaptchaService(){ //生成随机颜色,参数分别表示RGBA的取值范围 RandomRangeColorGenerator textColor = new RandomRangeColorGenerator(new int[]{0,255},new int[]{0,180},new int[]{0,210},new int[]{255,255}); //随机文字多少和颜色,参数1和2表示最少生成多少个文字和最多生成多少个 RandomTextPaster randomTextPaster = new RandomTextPaster(4, 5, textColor,true); //生成背景的大小这里是宽85高40的图片,也可以设置背景颜色和随机背景颜色,这里使用默认的白色 UniColorBackgroundGenerator colorbgGen = new UniColorBackgroundGenerator(85,40); //随机生成的字体大小和字体类型,参数1和2表示最小和最大的字体大小,第三个表示随机的字体 RandomFontGenerator randomFontGenerator = new RandomFontGenerator(20, 25, new Font[]{ new Font("Arial", 0, 10),new Font("Tahoma",0,10)}); //结合上面的对象构件一个从文本生成图片的对象 ComposedWordToImage cwti = new ComposedWordToImage(randomFontGenerator,colorbgGen,randomTextPaster); //随机文本的字典,这里是使用jcaptcha-1.0-all.jar中的文本字典,字典名称为toddlist.properties ComposeDictionaryWordGenerator cdwg = new ComposeDictionaryWordGenerator(new FileDictionary("toddlist")); GimpyFactory gf = new GimpyFactory(cdwg, cwti); GenericCaptchaEngine gce = new GenericCaptchaEngine(new CaptchaFactory[]{gf}); //返回一个Service对象,这里180是验证码存在的时间,单位是秒,200000是最大存储大小 return new GenericManageableCaptchaService(gce,180,200000,75000); }}
每一句代码都有注释,这里就不多说了。
3、创建一个生成验证码的Servlet,代码如下:
package cn.v5cn.jcaptchatest.custom; import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.IOException; 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.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageEncoder; public class CustomServlet extends HttpServlet { private static final long serialVersionUID = 169310818225761427L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { byte[] captChallengeAsJpeg = null; ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); String captchaId = req.getSession().getId(); BufferedImage challenge = CaptchaServiceSingleton.getService().getImageChallengeForID(captchaId,req.getLocale()); JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream); jpegEncoder.encode(challenge); captChallengeAsJpeg = jpegOutputStream.toByteArray(); resp.setHeader("Cache-Control", "no-store"); resp.setHeader("Pragma", "no-cache"); resp.setDateHeader("Expires", 0); resp.setContentType("image/jpeg"); ServletOutputStream respOutputStream = resp.getOutputStream(); respOutputStream.write(captChallengeAsJpeg); respOutputStream.flush(); respOutputStream.close(); }}
4、在Web.xml中注册这个Servlet,代码如下:
generateValidateCode cn.v5cn.jcaptchatest.custom.CustomServlet generateValidateCode /cgvc
5、编写一个使用验证码的页面,代码如下:
6、编写一个验证Servlet并在web.xml中注册,代码分别如下:
package cn.v5cn.jcaptchatest.custom; import java.io.IOException; import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class ValidateServlet extends HttpServlet { private static final long serialVersionUID = -7173743572400866269L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String captchaId = req.getSession().getId(); String validateCode = req.getParameter("customgvc"); boolean validateResult = CaptchaServiceSingleton.getService().validateResponseForID(captchaId, validateCode); if(validateResult) resp.sendRedirect("success.html"); else resp.sendRedirect("fail.html"); }}
validatServlet cn.v5cn.jcaptchatest.custom.ValidateServlet validatServlet /valiServlet
7、运行会看到验证码如下:
8、输入验证码点击提交,看是否可以验证通过,如果一切正常的话Session中的和提交的是一致的。
1.2、使用Spring配置jcaptha验证码
1、创建一个javaWeb工程并加入Spring和jcaptcha的包。添加完成后的包依赖如下:
2、在web.xml中配置Spring代码如下:
contextConfigLocation /WEB-INF/spring-jcaptcha.xml org.springframework.web.context.ContextLoaderListener
3、在WEB-INF中创建spring-jcaptcha.xml的SpringBean配置文件,代码如下:
各种配置与代码实现是一样的,每个配置中都有注释。
4、 编写一个生成验证码的Servlet,代码如下:
package cn.v5cn.jcaptchatest.spring; import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.IOException; import javax.imageio.ImageIO;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.beans.factory.BeanFactoryUtils;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; public class JcaptchaServlet extends HttpServlet { private static final long serialVersionUID = -8021621053846019170L; public static final String CAPTCHA_IMAGE_FORMAT = "jpeg"; private ImageCaptchaService captchaService; @Override public void init() throws ServletException { WebApplicationContext appCtx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); captchaService = (ImageCaptchaService) BeanFactoryUtils.beanOfTypeIncludingAncestors(appCtx, ImageCaptchaService.class); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { byte[] captchaChallengeAsJpeg = null; ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); try { String captchaId = request.getSession().getId(); BufferedImage challenge = captchaService.getImageChallengeForID( captchaId, request.getLocale()); ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream); } catch (IllegalArgumentException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch (CaptchaServiceException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); // flush it in the response response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/" + CAPTCHA_IMAGE_FORMAT); ServletOutputStream responseOutputStream = response.getOutputStream(); responseOutputStream.write(captchaChallengeAsJpeg); responseOutputStream.flush(); responseOutputStream.close(); }}
5、在web.xml中注册这Servlet,代码如下:
springCaptcha cn.v5cn.jcaptchatest.spring.JcaptchaServlet springCaptcha /scgvc
6、验证步骤与代码实现一样,请大家自行编写。
二、kaptcha验证码使用
个人感觉kaptcha使用比jcaptcha相对简单。
1、在Servelt中配置kaptcha的Servlet,代码如下:
kaptcha com.google.code.kaptcha.servlet.KaptchaServlet kaptcha.border no kaptcha.textproducer.font.color black kaptcha.textproducer.char.space 5 kaptcha /kaptcha.jpg
kaptcha.border:是否显示边框。
kaptcha.textproducer.font.color:字体颜色
kaptcha.textproducer.char.space:字符间距
更多的属性设置可以在com.google.code.kaptcha.Constants类中找到。其中包括:
kaptcha.border.color:边框颜色
kaptcha.border.thickness:边框宽度
kaptcha.textproducer.char.length:产生字符的长度
kaptcha.textproducer.font.size:产生字符的大小
kaptcha.image.width:产生图片的宽度
kaptcha.image.height:产生图片的高度,等
2、编写一个显示验证码的页面,代码如下:
3、运行页面显示如下:
4、 编写一个验证的Servelt,代码如下:
package cn.v5cn.kaptcha; import java.io.IOException; import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; import com.google.code.kaptcha.Constants; public class KaptchaValidateServlet extends HttpServlet { private static final long serialVersionUID = -7642000788132875193L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String validate = req.getParameter("kaptchaValidate"); String validateCode = (String) req.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY); if(validate==null || validateCode == null){ resp.sendRedirect("fail.html"); }else if(!validateCode.equals(validate)){ resp.sendRedirect("fail.html"); }else{ resp.sendRedirect("success.html"); } }}
三、总结:
到处jcaptcha和kaptcha的验证代码就编写完成了,写的还比较浅显。希望对需要这两个验证码包的朋友有所帮助,也是给自己一个备忘。
全引用自: 此条目由发表在分类目录,并贴了、、标签。将加入收藏夹。