以下為項目中所用代碼,文筆有限,直接上代碼。
所需jar包:
是否需要其他依賴包,不詳
web.xml
Jcaptcha com.bkgd.cms.servlet.JcaptchaServlet Jcaptcha /http://blog.csdn.net/itmyhome1990/article/details/captcha.svl
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(); } }
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; } }
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)); } }
HttpServletRequest request = ServletActionContext.getRequest(); String sessID = request.getSession().getId(); Boolean isResponseCorrect = JCaptchaServiceSingleton.getInstance().validateResponseForID(sessID, checkCode); if(isResponseCorrect){ return "true" }else{ return "false" }