以下为项目中所用代码,文笔有限,直接上代码。
所需jar包:
是否需要其他依赖包,不详
web.xml
<servlet> <servlet-name>Jcaptcha</servlet-name> <servlet-class>com.bkgd.cms.servlet.JcaptchaServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Jcaptcha</servlet-name> <url-pattern>/captcha.svl</url-pattern> </servlet-mapping>
需要一个服务类 生成Image
package com.bkgd.cms.servlet; import java.awt.image.BufferedImage; 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 org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.log4j.Logger; import com.octo.captcha.service.CaptchaServiceException; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; @SuppressWarnings("serial") public class JcaptchaServlet extends HttpServlet { public static final String CAPTCHA_IMAGE_FORMAT = "jpeg"; private static final Logger log = Logger.getLogger(JcaptchaServlet.class); @Override public void init() throws ServletException { } /** * @step1 本方法使用Jcaptcha工具生成img图片,并输出到客户端 * @step2 将来在用户提交的action中插入下面语句进行验证码的校验:Boolean isResponseCorrect = * captchaService.validateResponseForID( captchaId, ""); **/ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { byte[] captchaChallengeAsJpeg = null; ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); try { // 借助于HttpSession ID存储Captcha ID,开发者也可以借助于其他惟一值 String captchaId = request.getSession().getId(); // 获得GMailEngine使用的图片内容 BufferedImage challenge = JCaptchaServiceSingleton.getInstance().getImageChallengeForID(captchaId, request.getLocale()); // 输出JPEG格式 JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream); jpegEncoder.encode(challenge); } catch (IllegalArgumentException e) { log.error(e); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch (CaptchaServiceException e) { log.error(e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); // 输出JPEG图片 response.setContentType("image/jpeg"); ServletOutputStream responseOutputStream = response.getOutputStream(); responseOutputStream.write(captchaChallengeAsJpeg); responseOutputStream.flush(); responseOutputStream.close(); } }
JCaptchaServiceSingleton
package com.bkgd.cms.servlet; import com.octo.captcha.service.captchastore.FastHashMapCaptchaStore; import com.octo.captcha.service.image.DefaultManageableImageCaptchaService; import com.octo.captcha.service.image.ImageCaptchaService; public class JCaptchaServiceSingleton { private static ImageCaptchaService imageCaptchaService = new DefaultManageableImageCaptchaService( new FastHashMapCaptchaStore(), new GMailEngine(), 180, 100000, 75000); public static ImageCaptchaService getInstance() { return imageCaptchaService; } }
验证码样式的图片引擎GMailEngine
package com.bkgd.cms.servlet; import java.awt.Color; import java.awt.Font; import java.awt.image.ImageFilter; import com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator; import com.octo.captcha.component.image.backgroundgenerator.UniColorBackgroundGenerator; import com.octo.captcha.component.image.color.RandomListColorGenerator; import com.octo.captcha.component.image.deformation.ImageDeformation; import com.octo.captcha.component.image.deformation.ImageDeformationByFilters; 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.TextDecorator; import com.octo.captcha.component.image.wordtoimage.DeformedComposedWordToImage; 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; /** * 仿照JCaptcha2.0编写GMail验证码样式的图片引擎. */ public class GMailEngine extends ListImageCaptchaEngine { @Override protected void buildInitialFactories() { int minWordLength = 4; int maxWordLength = 4; int fontSize = 26; int imageWidth = 110; int imageHeight = 50; //在页面上将显示的内容 WordGenerator dictionnaryWords = new RandomWordGenerator("1234567890"); TextPaster randomPaster = new DecoratedRandomTextPaster(minWordLength, maxWordLength, new RandomListColorGenerator( new Color[] { new Color(0, 0, 0) }), new TextDecorator[] {}); BackgroundGenerator background = new UniColorBackgroundGenerator( imageWidth, imageHeight, Color.white); FontGenerator font = new RandomFontGenerator(fontSize, fontSize, new Font[] { new Font("nyala", Font.BOLD, fontSize), new Font("Bell MT", Font.PLAIN, fontSize), new Font("Credit valley", Font.BOLD, fontSize) }); ImageDeformation postDef = new ImageDeformationByFilters(new ImageFilter[] {}); ImageDeformation backDef = new ImageDeformationByFilters(new ImageFilter[] {}); ImageDeformation textDef = new ImageDeformationByFilters(new ImageFilter[] {}); WordToImage word2image = new DeformedComposedWordToImage(font, background, randomPaster, backDef, textDef, postDef); addFactory(new GimpyFactory(dictionnaryWords, word2image)); } }
前台JSP
<input class="input" type="text" name="checkCode" id="checkCode" value=""/> <img id="captcha" src="captcha.svl" onclick="this.src='captcha.svl?d='+new Date()*1"/>
后台Action验证
HttpServletRequest request = ServletActionContext.getRequest(); String sessID = request.getSession().getId(); Boolean isResponseCorrect = JCaptchaServiceSingleton.getInstance().validateResponseForID(sessID, checkCode); if(isResponseCorrect){ return "true" }else{ return "false" }