Verification code generation component-Use of JCaptcha

Source: Internet
Author: User

The following is the code used in the project. The document is limited and you can directly use the code.

Jar package:

Whether other dependent packages are required. Unknown


Web. xml

      
  
   Jcaptcha
       
  
   com.bkgd.cms.servlet.JcaptchaServlet
  
 
      
  
   Jcaptcha
       
  
   /http://blog.csdn.net/itmyhome1990/article/details/captcha.svl
  
 

A service class is required to generate an 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. export codec; import com.sun.image.codec.jpeg. required imageencoder; @ SuppressWarnings ("serial") public class JcaptchaServlet extends HttpServlet {public static final String CAPTCHA_IMAGE_FORMAT = "jpeg"; private static final Logger log = Logger. getLogger (JcaptchaServlet. class); @ Overridepublic void init () throws ServletException {}/*** @ step1 This method uses the Jcaptcha tool to generate an img image, output to the client * @ step2 and insert the following statement into the action submitted by the user to verify the verification code: Boolean isResponseCorrect = * captchaService. validateResponseForID (captchaId, ""); ** // @ Overrideprotected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {byte [] response = null; byteArrayOutputStream extends outputstream = new ByteArrayOutputStream (); try {// store the Captcha ID by using the HttpSession ID. developers can also use other unique values String captchaId = request. getSession (). getId (); // obtain the image content used by GMailEngine BufferedImage challenge = JCaptchaServiceSingleton. getInstance (). getImageChallengeForID (captchaId, request. getLocale (); // output JPEG format: Required imageencoder required encoder = required codec. createJPEGEncoder (extends outputstream); extends encoder. 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 = extends outputstream. toByteArray (); response. setHeader ("Cache-Control", "no-store"); response. setHeader ("Pragma", "no-cache"); response. setDateHeader ("Expires", 0); // output JPEG image 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;}}

Verification Code-style Image Engine 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;/*** the image engine used to write the GMail Verification Code style in the format of JCaptcha2.0. */public class GMailEngine extends ListImageCaptchaEngine {@ Overrideprotected void equals () {int minWordLength = 4; int maxWordLength = 4; int fontSize = 26; int imageWidth = 110; int imageHeight = 50; // The display content 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 partition (new ImageFilter [] {}); WordToImage word2image = new partition (font, background, randomPaster, backDef, textDef, postDef); addFactory (new GimpyFactory (dictionnaryWords, word2image ));}}

Foreground JSP

 

Background Action Verification

HttpServletRequest request = ServletActionContext.getRequest();String sessID = request.getSession().getId();Boolean isResponseCorrect = JCaptchaServiceSingleton.getInstance().validateResponseForID(sessID, checkCode);if(isResponseCorrect){return "true"}else{return "false"}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.