Verification Code SimpleCaptcha

Source: Internet
Author: User

I want to sum up the verification code (the verification code used for open source. Of course, you can also implement it on your own, but you can use it for mature open-source projects.) After reading several open-source projects, we found that SimpleCaptcha is easy to use, start with it.

Contact SimpleCaptcha

1. Download SimpleCaptcha

2. Add the downloaded JAR package to the project.

3. Configure Servlet

Available servlets: StickyCaptchaServlet, SimpleCaptchaServlet, and AudioCaptchaServlet.

StickyCaptchaServlet and SimpleCaptchaServlet generate image verification codes, and AudioCaptchaServlet generate voice verification codes.

The verification code generated by StickyCaptchaServlet will be saved in the session, and refresh will not be re-created.

StickyCaptchaServletAre "sticky" to the user's session: page reloads will render the same CAPTCHA instead of generating a new one.

The following is an example of simple servlet configuration. The generated verification code is displayed on the page.

Servlet Configuration

 1     <servlet> 2         <servlet-name>StickyCaptcha</servlet-name> 3         <servlet-class>nl.captcha.servlet.StickyCaptchaServlet</servlet-class> 4     </servlet> 5     <servlet> 6         <servlet-name>SimpleCaptcha</servlet-name> 7         <servlet-class>nl.captcha.servlet.SimpleCaptchaServlet</servlet-class> 8     </servlet> 9     <servlet>10         <servlet-name>AudioCpatcha</servlet-name>11         <servlet-class>nl.captcha.servlet.AudioCaptchaServlet</servlet-class>12     </servlet>13 14     <servlet-mapping>15         <servlet-name>StickyCaptcha</servlet-name>16         <url-pattern>/sticky.png</url-pattern>17     </servlet-mapping>18     <servlet-mapping>19         <servlet-name>SimpleCaptcha</servlet-name>20         <url-pattern>/simple</url-pattern>21     </servlet-mapping>22     <servlet-mapping>23         <servlet-name>AudioCpatcha</servlet-name>24         <url-pattern>/audio</url-pattern>25     </servlet-mapping>

 

Display page

1 <table> 2 <tr valign = "top"> 3 <td> Sticky: </td> 4 <td>  5 </td> 6 </tr> 7 <tr valign =" top "> 8 <td> Simple: </td> 9 <td>  10 </td> 11 </tr> 12 <tr valign =" top "> 13 <td> Audio: </td> 14 <td> <audio id = "audio" src = "http: // localhost: 8080/captcha/audio "15 controls =" controls "> the browser does not support & lt; audio & gt; </audio> </td> 16 </tr> 17 </table>

 

Why do I upload three files? Of course it's not boring. The three items are refreshed in sequence. I found that the verification code of the Sticky part has changed after refreshing, which is inconsistent with the above description. Then, we tried to put only one Sticky verification code on the page, and the refresh did not change. Why? Observe the image and find that the content of Sticky is the last Simple content every time you refresh it ...... they all store content in the session, and the stored AttributeName is the same, so they are overwritten.

Print the session content and find that Sticky and Simple are saved in the session name simpleCaptcha (constant Captcha. NAME); The NAME stored by Audio is audioCaptcha (constant AudioCaptcha. NAME), so you can use attributeName to retrieve objects from the session and convert them into Captcha or AudioCaptcha. Then, you can use the getAnswer method to obtain the answer to the Verification code, or use isCorrect (String answer) verify whether the entered verification code is correct.

In use, it is also found that StickyCaptchaServlet cannot normally produce returned content during initial loading. In http://simplecaptcha.git.sourceforge.net/git/gitweb.cgi? P = simplecaptcha/simplecaptcha; a = commit; h = 4c3a9eddfefabab6492c89f5c3887ca622ce4b0f: the bug has been fixed but still appears during use.

Sticky is not commonly used. According to the current verification code habits, the verification code is refresh the page to regenerate.

The above example only shows the effect of the basic verification code, which is not verified. The following is correct when the user inputs the content.

Form

1 <form action = "http: // localhost: 8080/captcha/answer. jsp "method =" post "> 2 <table> 3 <tr valign =" top "> 4 <td> Simple: </td> 5 <td>  6 </td> 7 <td> <input type =" text "name =" simpleAnswer "/> 8 </td> 9 </tr> 10 11 <tr valign = "top"> 12 <td> Audio: </td> 13 <td> <audio id = "audio" src = "http: // localhost: 8080/captcha/audio "14 controls =" controls "> the browser does not support & lt; audio & gt; </audio> 15 </td> 16 <td> <input name = "audioAnswer"/> 17 </td> 18 </tr> 19 </table> 20 <input type = "submit" value = "submit"/> 21 </form>

The JSP that receives and judges whether the verification code is correct.

Verify JSP

 1 <% 2         Captcha captcha = (Captcha) session.getAttribute(Captcha.NAME); 3         AudioCaptcha audioCaptcha = (AudioCaptcha) session 4                 .getAttribute(AudioCaptcha.NAME); 5         if (captcha.getAnswer() 6                 .equals(request.getParameter("simpleAnswer"))) { 7     %> 8     <B> Simple:Correct!</B> 9     <br />10     <%11         } else {12     %>13     <B> Simple:Wrong!</B>14     <br />15     <%16         }17         if (captcha.isCorrect(request.getParameter("audioAnswer"))) {18     %>19     <B> Audio:Correct!</B>20     <%21         } else {22     %>23     <B> Audio:Wrong!</B>24     <%25         }26     %>

Audio is also a pain point and is not commonly used at present. After all, voice verification applications require that the client must have voice output and user requirements, poor listening ......

Else ---------------------------------------------------------------------------------------------------------------------------------

The Servlet included in the simplecaptcha package is used to generate and verify simple verification codes. The following Code expands simplecaptcha to implement custom verification codes.

Write the Servlet to receive the Verification Code request, use Captcha. build () to generate the verification code, and write the image content to the returned stream. so easy ......

How to generate a verification code

1 @ Override 2 protected void doPost (HttpServletRequest req, HttpServletResponse resp) 3 throws ServletException, IOException {4 // simply set the image length and width and add content 5 Captcha captcha = new Captcha. builder (120, 38 ). addText (). build (); 6 resp. setContentType ("image/jpeg"); 7 OutputStream OS = resp. getOutputStream (); 8 ImageIO. write (captcha. getImage (), "JPEG", OS); 9 req. getSession (). setAttribute ("checkCode", captcha. getAnswer (); 10}

The above code stores the answer to the Verification code in the session. After you enter the verification code and submit it, you can compare the content entered by the user with the content in the session to verify whether it is correct.

Further, restrict the content of the Verification Code, remove confusing content such as 0, 1, l, and O, restrict the font, set the background, and so on ......

AddBackground () uses the default BackgroundProducer to add a background. addBackground (BackgroundProducer) can provide its own background generator by implementing the BackgroundProducer interface.

AddBorder () draws a border with a pixel width around the image.

AddNoise () and addNoise (NoiseProducer nProd) respectively set "noise" through the default and provided NoiseProducer ". Add a horizontal line to the image by default.

Gimp () and gimp (GimpyRenderer gimpy) blur images through the default or GimpyRenderer.

AddText () uses the default TextProducer to create the verification code content.

AddText (TextProducer txtProd) uses the provided TextProducer to create the verification code content.

AddText (TextProducer txtProd, WordRenderer wRenderer) uses the provided TextProducer to create the verification code content and uses the provided WordRenderer to render the content.

AddText (WordRenderer wRenderer) uses the default TextProducer to create the verification code content and uses the provided WordRenderer to render the content.

 

Build () creates a Captcha object.

Let's give two decent results: Custom TextProducer and wordrander.

EasyCharTextProducer

 1 public class EasyCharTextProducer implements TextProducer { 2  3     private static final char[] chars = { 'a', 'c', 'd', 'e', 'f', 'h', 'j', 4             'k', 'm', 'n', 'p', 'r', 's', 't', 'w', 'x', 'y', '3', '4', '5', 5             '7', '8' }; 6  7     private static final int lastChar = chars.length; 8  9     private int length;10 11     public EasyCharTextProducer() {12         this(5);13     }14 15     public EasyCharTextProducer(int length) {16         super();17         this.length = length;18     }19 20     public String getText() {21         Random random = new Random();22         StringBuilder sb = new StringBuilder(length);23         for (int i = 0; i < length; i++) {24             int r = random.nextInt(lastChar);25             sb.append(chars[r]);26         }27         return sb.toString();28     }29 30 }
FixedWordRenderer

 1 public class FixedWordRenderer implements WordRenderer { 2     // The text will be rendered 25%/5% of the image height/width from the X and 3     // Y axes 4     private static final double YOFFSET = 0.20; 5     private static final double XOFFSET = 0.15; 6     private static final int charDistance = 5; 7     private static final Color DEFAULT_COLOR = Color.BLACK; 8     private static final List<Font> DEFAULT_FONTS = new ArrayList<Font>(); 9 10     private final Color _color;11     private final List<Font> _fonts;12 13     static {14         DEFAULT_FONTS.add(new Font("Arial", Font.BOLD, 40));15         DEFAULT_FONTS.add(new Font("Courier", Font.BOLD, 40));16     }17 18     /**19      * Will render the characters in black and in either 40pt Arial or Courier.20      */21     public FixedWordRenderer() {22         this(DEFAULT_COLOR, DEFAULT_FONTS);23     }24 25     public FixedWordRenderer(Color color, List<Font> fonts) {26         _color = color != null ? color : DEFAULT_COLOR;27         _fonts = fonts != null ? fonts : DEFAULT_FONTS;28     }29 30     /**31      * Render a word onto a BufferedImage.32      * 33      * @param word34      *            The word to be rendered.35      * @param bi36      *            The BufferedImage onto which the word will be painted on to37      */38     public void render(String word, BufferedImage image) {39         Random random = new Random();40         Graphics2D g = image.createGraphics();41 42         RenderingHints hints = new RenderingHints(43                 RenderingHints.KEY_ANTIALIASING,44                 RenderingHints.VALUE_ANTIALIAS_ON);45         hints.add(new RenderingHints(RenderingHints.KEY_RENDERING,46                 RenderingHints.VALUE_RENDER_QUALITY));47         g.setRenderingHints(hints);48 49         g.setColor(_color);50         FontRenderContext frc = g.getFontRenderContext();51         int startPosX = (int) Math.round(image.getWidth() * XOFFSET);52         int startPosY = image.getHeight()53                 - (int) Math.round(image.getHeight() * YOFFSET);54         char[] wc = word.toCharArray();55         for (char element : wc) {56             char[] itchar = new char[] { element };57             int choiceFont = random.nextInt(_fonts.size());58             Font itFont = _fonts.get(choiceFont);59             g.setFont(itFont);60 61             GlyphVector gv = itFont.createGlyphVector(frc, itchar);62             double charWitdth = gv.getVisualBounds().getWidth();63 64             g.drawChars(itchar, 0, itchar.length, startPosX, startPosY);65             startPosX = startPosX + (int) charWitdth66                     + random.nextInt(charDistance) - 2;67         }68     }69 70 }

Create Captcha code and corresponding results

1 Captcha captcha = new Captcha.Builder(120, 38)2                 .addText(new EasyCharTextProducer(4),3                         new FixedWordRenderer(Color.white, englishFonts))4                 .addNoise()5                 .addNoise(new CurvedLineNoiseProducer(Color.gray, 1.5f))6                 .addBorder().addBackground(new GradiatedBackgroundProducer()).build();

1 Captcha captcha = new Captcha.Builder(120, 38)2                 .addText(new EasyCharTextProducer(4),3                         new FixedWordRenderer(Color.white, englishFonts))4                 .gimp(new FishEyeGimpyRenderer()).addBorder().build();

To achieve better results, you need to understand the randerer and producer effects provided under the gimpy, noise, and background packages and implement the interfaces to provide your own randerer and producer. Of course, aesthetics is very important ......

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.