Use patchca in Java to generate a verification code

Source: Internet
Author: User

PatchcaIt is an open-source Java verification code library written by Piotr piastucki. It is packaged into a jar file and released. patchca is simple to use but powerful.

In this example, the custom background is implemented. Because the generated image is small and the text is not displayed completely when the fluctuation is too large, the filter attribute is changed.

:

The Code is as follows:

Package COM. ninemax. cul. servlet; import Java. AWT. color; import Java. AWT. graphics; import Java. AWT. image. bufferedimage; import Java. AWT. image. bufferedimageop; import Java. io. ioexception; import Java. io. outputstream; import Java. util. arraylist; import Java. util. list; import Java. util. random; import javax. imageIO. imageIO; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import javax. servlet. HTTP. httpsession; import Org. patchca. background. backgroundfactory; import Org. patchca. color. colorfactory; import Org. patchca. color. randomcolorfactory; import Org. patchca. filter. configurablefilterfactory; import Org. patchca. filter. library. abstractimageop; import Org. patchca. filter. library. wobbleimageop; import Org. patchca. font. randomfontfactory; import Org. patchca. service. CAPTCHA; import Org. patchca. service. configurablecaptchaservice; import Org. patchca. text. renderer. bestfittextrenderer; import Org. patchca. text. renderer. textrenderer; import Org. patchca. word. randomwordfactory;/*** verification code generation class ** use the open source verification code project patchca to generate * dependent jar package: patchca-0.5.0.jar * project URL: https://code.google.com/p/patchca/ ** @ author zyh * @ Version 1.00 2012-7-12 New */public class validationcodeservlet extends httpservlet {Private Static final long serialversionuid = empty; private incluconfigurablecaptchaservice = NULL; private colorfactory = NULL; private randomfontfactory fontfactory = NULL; private randomwordfactory wordfactory = NULL; private textrenderer = NULL; Public validationcodeservlet () {super ();}/*** servlet destruction method, destroys the resources used. <br> */Public void destroy () {wordfactory = NULL; colorfactory = NULL; fontfactory = NULL; textrenderer = NULL; ableablecaptchaservice = NULL; super. destroy (); // just puts "Destroy" string in log} public void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {dopost (request, response );} public void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {response. setcontenttype ("image/PNG"); response. setheader ("cache", "No-Cache"); httpsession session = request. getsession (true); outputstream = response. getoutputstream (); // get the verification code object, which contains the verification code image and the verification code string CAPTCHA = ableablecaptchaservice. getcaptcha (); // enter sessionstring validationcode = CAPTCHA to obtain the verification code string. getchallenge (); Session. setattribute ("validationcode", validationcode); // obtain the verification code image and output bufferedimage = CAPTCHA. getimage (); ImageIO. write (bufferedimage, "PNG", outputstream); outputstream. flush (); outputstream. close ();}/*** servlet Initialization Method */Public void Init () throws servletexception {configurablecaptchaservice = new configurablecaptchaservice (); // Color Creation factory, use a random color range of colorfactory = new randomcolorfactory (); configurablecaptchaservice. setcolorfactory (colorfactory); // random font generator fontfactory = new randomfontfactory (); fontfactory. setmaxsize (32); fontfactory. setminsize (28); configurablecaptchaservice. setfontfactory (fontfactory); // random character generator to remove confusing letters and numbers, such as O and 0 wordfactory = new randomwordfactory (); wordfactory. setcharacters ("abcdefghkmnpqstwxyz23456789"); wordfactory. setmaxlength (5); wordfactory. setminlength (4); configurablecaptchaservice. setwordfactory (wordfactory); // custom Verification Code image background mycustombackgroundfactory backgroundfactory = new mycustombackgroundfactory (); configurablecaptchaservice. setbackgroundfactory (backgroundfactory); // set configurablefilterfactory filterfactory = new configurablefilterfactory (); List <items> filters = new arraylist <items> (); wobbleimageop = new items (); wobbleimageop. setedgemode (abstractimageop. edge_mirror); wobbleimageop. setxamplop (2.0); wobbleimageop. setyamplications (1.0); filters. add (wobbleimageop); filterfactory. setfilters (filters); configurablecaptchaservice. setfilterfactory (filterfactory); // set textrenderer to new bestfittextrenderer (); textrenderer. setbottommargin (3); textrenderer. settopmargin (3); configurablecaptchaservice. settextrenderer (textrenderer); // The image size of the Verification Code ableablecaptchaservice. setwidth (82); configurablecaptchaservice. setheight (32);}/*** custom Verification Code image background, mainly draws noise and interference lines */private class mycustombackgroundfactory implements backgroundfactory {private random = new random (); public void fillbackground (bufferedimage image) {graphics = image. getgraphics (); // the width and height of the Verification Code image int imgwidth = image. getwidth (); int imgheight = image. getheight (); // fill in the white background graphics. setcolor (color. white); graphics. fillrect (0, 0, imgwidth, imgheight); // draw 100 noises (random color and position) for (INT I = 0; I <100; I ++) {// random color int RINT = random. nextint (255); int Gint = random. nextint (255); int bint = random. nextint (255); graphics. setcolor (new color (RINT, Gint, Bint); // random position int xint = random. nextint (imgwidth-3); int yint = random. nextint (imgheight-2); // random rotation angle int sangleint = random. nextint (360); int eangleint = random. nextint (360); // random size int Wint = random. nextint (6); int hint = random. nextint (6); graphics. fillarc (xint, yint, Wint, hint, sangleint, eangleint); // draw 5 interference lines if (I % 20 = 0) {int xint2 = random. nextint (imgwidth); int yint2 = random. nextint (imgheight); graphics. drawline (xint, yint, xint2, yint2 );}}}}}

The Web. xml configuration is as follows:

<servlet>    <servlet-name>validationCode</servlet-name>    <servlet-class>com.ninemax.cul.servlet.ValidationCodeServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>validationCode</servlet-name>    <url-pattern>/validationCodeServlet.png</url-pattern>  </servlet-mapping>

JSP reference (Part ):

/validationcodeservlet.png" onclick = "refreshcode (this) "/> <a id =" arecode "href =" javascript: void (0); "onclick =" refreshcode () "> change one </a>

JS reload image method (reference ):

/*** Refresh the Verification Code * @ Param imgobj Verification Code IMG element */function refreshcode (imgobj) {If (! Imgobj) {imgobj = Document. getelementbyid ("validationcode");} var Index = imgobj. SRC. indexof ("? "); If (index! =-1) {var url = imgobj. SRC. substring (0, index + 1); imgobj. src = URL + math. random ();} else {imgobj. src = imgobj. SRC + "? "+ Math. Random ();}}
Related Article

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.