Single Function Learning-simple verification code-Verification Code

Source: Internet
Author: User

Single Function Learning-simple verification code-Verification Code

I. Functions of the Verification Code

1. prevent repeated requests. Generally, a verification code is required during login. The verification code is used to delay the time, so that the operation interval for each login is longer, so as to prevent brute force password cracking.

 

Ii. Design Ideas

1. The simplest verification code is a string of numbers. When I was a child, I saw four numbers.

2. This string of numbers should be random.

3. This string of numbers can be changed (the previous button is changed ).

4. Enter a verification code in the input box.

5. The verification code should be changed if logon fails.

6. A little advanced, the verification code can be converted into an image to prevent malicious software from directly obtaining the verification code value from the front-end code.

7. For more advanced verification codes, you can change the verification content, such as verifying Chinese characters and verifying the calculation result. You can change the verification method, such as 12306 to view the name selection chart, such as dragging the image for verification; you can change the verification code acquisition method. For example, you can send the verification code to your mobile phone by text message or phone, or by email to your mailbox. (This item is slightly more difficult. Ignore it here)

 

Iii. Code Implementation

1. The simplest Verification Code

① Front-end

1 <div class = "yanzhengma"> 2 <span> Verification Code: </span> 3 <input type = "text" name = "yanzhengma" placeholder = "Enter the verification code"> 4 <span id = "yanzhengmaInfo"> 1234 </span> 5 <span onclick = "changeYanzhengmaInfo (); "> change one </span> 6 </div>

 

// Function changeYanzhengmaInfo () {var url = contextPath + '/changeYanzhengmaInfo.html? '+ New Date (). getTime (); $. post (url, function (data) {$ ("# yanzhengmaInfo"). text (data );});}

 

② Backend

1 // generate Verification Code 2 @ Action ("/changeYanzhengmaInfo") 3 public void changeYanzhengmaInfo () {4 // generate a random number, four digits, less than four digits (less than 1000, set a value. For a value greater than 9999, set a value of 5 Random random = new Random (); 6 int r = random. nextInt (10000); 7 if (r <1000) {8 r = 2018; 9} else if (r> 9999) {10 r = 9999; 11} 12 final String yanzhengma = random. nextInt (10000) + ""; 13 // Save the value to session14 final HttpSession session = ServletActionContext. getReq Uest (). getSession (); 15 session. setAttribute ("captcha", yanzhengma); 16 // return the value to the frontend 17 this. sendResponseMsg (yanzhengma); 18} 19 20/** 21 * Verification code. 22*23 * @ throws UnsupportedEncodingException24 * @ author 25 */26 @ Action ("/checkCaptcha") 27 public void checkCaptcha () throws UnsupportedEncodingException {28 this. request. setCharacterEncoding (ENCODE_UTF_8); 29 this. response. setContentType (CONTENT_TYPE); 30 fin Al String yanzhengma = this. request. getParameter ("yanzhengma"); 31 32 String captcha = this. session. get ("captcha"); 33 if (captcha = null) {34 sendFailMsg ("", "The Verification Code does not exist. Please refresh it! "); 35 return; 36} 37 if (captcha. equals (yanzhengma) {38 this. sendSuccessMsg (); 39} else {40 this. sendFailMsg (null, "Verification code error! "); 41} 42}

 

 

2. Image Verification Code

① Front-end

Different from the above, the verification code obtained here is an image, so the data to be obtained from the background should be a link to the Verification Code image. You can change the verification code by changing the link.

<Li> <label class = "u_label"> Verification Code: </label> <input id = "captcha" class = "text-input captcha" name = "captcha" type = "text" placeholder = "Enter the verification code"> <a href = "javascript :; "style =" margin-left: 20px; ">  </a> <span> <a href = "javascript: changeCaptchaImg (); "style =" height: 40px; line-height: 40px; margin-left: 10px; "> change one </a> </span> </li> <span id =" captchadwrong "style =" margin-left: 84px; color: red; display: none "> enter the correct Verification Code </span>

 

1 // modify the link to get the image. 2 function changeCaptchaImg () {3 var imgUrl = contextPath + '/captchaImage.html? '+ New Date (). getTime (); 4 $ ('# captcha-img '). attr ('src', imgUrl); 5} 6 7 // verify the verification code 8 function checkCaptcha () {9 var captchaValue = $ ("input [name = 'captcha ']"). val (); 10 var captcha = false; 11 var captchadwrong = $ ('# captchadwrong'); 12 $. ajax ({13 url: contextPath + '/checkCaptcha.html', 14 type: 'post', 15 ype: 'json', 16 async: false, 17 data: {captcha: captchaValue}, 18 success: function (text) {19 captcha = text. success; 20} 21}); 22 if (captcha = false) {// failure 23 captchadwrong.css ('display', "inline-block"); 24 captchadwrong. text ("enter the correct Verification Code"); 25 return false; 26} else {// success 27 captchadwrong.css ('display', "none"); 28 return true; 29} 30}

 

② Backend

First, you need to introduce a jar package: simplecaptcha-1.2.1.jar

1 @ Action ("/captchaImage") 2 public void createCaptchaImage () {3 // custom Set Font color and size the simplest effect multiple fonts random display 4 final List <java. awt. color> textColors = Arrays. asList (this. getRandColor (50,200), this. getRandColor (50,200); 5 final List <Font> fontList = Lists. newArrayList (); 6 fontList. add (new Font ("Viner Hand ITC", Font. type‑font, 52); // you can set 7 fontList, such as italic. add (new Font ("Kristen ITC", Font. ITALIC, 45); 8 f OntList. add (new Font ("Bradley Hand ITC", Font. HANGING_BASELINE, 52); 9 fontList. add (new Font ("Comic Sans ms", Font. PLAIN, 45); 10 // background of the image (gradient, from white to white) 11 final GradiatedBackgroundProducer gbp = new GradiatedBackgroundProducer (Color. white, Color. white); 12 // generate the verification code object, including the value Answer, time Timestamp, and Image. The Image contains the color and width information 13 final Captcha captcha = new Captcha. builder (CAPTCHA_WIDTH, CAPTCHA_HEIGHT ). ad DNoise (). addNoise () 14 //. gimp (new ShearGimpyRenderer15 // (this. getRandColor (50,200) 16. addText (new defatexttextproducer (RANDOM_NUMBER, MY_CHARS), 17 new DefaultWordRenderer (textColors, fontList) 18. addBackground (gbp ). build (); 19 // store the generated Verification Code 20 final HttpSession session = ServletActionContext in the session. getRequest (). getSession (); 21 OutputStream out = null; 22 try {23 out = this. response. getOutput Stream (); 24 this. response. reset (); 25 this. response. setContentType ("image/jpeg"); 26 this. response. setHeader ("Pragma", "No-cache"); 27 this. response. setHeader ("Cache-Control", "no-cache"); 28 this. response. setDateHeader ("Expires", 0); 29 ImageIO. write (captcha. getImage (), "JPG", out); 30 session. setAttribute (CAPTCHA, captcha); 31 out. flush (); 32 out. close (); 33 this. response. flushBuffer (); 34} catch (final IOException e) {35 CaptchaImageAction. LOGGER. error ("sending Verification Code IO exception", e); 36} finally {37 if (out! = Null) {38 try {39 out. close (); 40} catch (final IOException e) {41 CaptchaImageAction. LOGGER. error ("sending Verification Code IO exception", e ); 42} 43} 44} 45} 46 47 48/* 49 * random Color 50 */51 private Color getRandColor (final int fc, final int bc) in a given range) {52 int tmpFc = fc; 53 int tmpBc = bc; 54 final Random random = new Random (); 55 if (tmpFc> MAX_RANDOM_NUMBER) {56 tmpFc = MAX_RANDOM_NUMBER; 57} 58 if (tmpBc> MAX_RANDOM_NUMBER) {5 9 tmpBc = MAX_RANDOM_NUMBER; 60} 61 final int r = tmpFc + random. nextInt (tmpBc-tmpFc); 62 final int g = tmpFc + random. nextInt (tmpBc-tmpFc); 63 final int B = tmpFc + random. nextInt (tmpBc-tmpFc); 64 return new Color (r, g, B); 65} 66 67 68/** 69 * Verification code. 70*71 * @ throws UnsupportedEncodingException72 * @ author73 */74 @ Action ("/checkCaptcha") 75 public void checkCaptcha () throws UnsupportedEncodingEx Ception {76 this. request. setCharacterEncoding (ENCODE_UTF_8); 77 this. response. setContentType (CONTENT_TYPE); 78 final String captcha = this. request. getParameter (CaptchaImageAction. CAPTCHA); 79 80 Object object = this. session. get (CaptchaImageAction. CAPTCHA); 81 if (object = null) {82 sendFailMsg ("", "The Verification Code does not exist. Please refresh it! "); 83 return; 84} 85 final Captcha captchaInSession = (Captcha) object; 86 final String answer = captchaInSession. getAnswer (); 87 // case-insensitive 88 if (answer. equalsIgnoreCase (captcha) {89 this. sendSuccessMsg (); 90} else {91 this. sendFailMsg (null, "Verification code error! "); 92} 93}

 

③

    

    

 

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.