Preface: Previously done a project, just open when the verification code is in the front-end to generate the front-end verification, and later felt that not reliable, the other is to retrieve the password function also need to send mail and SMS verification code, so, the verification code must be generated in the backend and saved to the application session only line! So, there is the following simple code, although the code is simple, but it is also a way to generate a verification code, in this small note for later use.
1: The following is the generation of verification code, test generated verification code method, relatively simple, the comments are relatively clear, not much said
Packagestart;ImportJava.util.Random; Public classHellomain {/*** Main function, as the entrance to call and test generate Captcha method *@paramargs*/ Public Static voidMain (string[] args) { for(inti=0; i<10;i++) {System.out.println ("" "+i+" "" + "" The Verification Code is "" +createverificationcode (6)); } } /*** Generate verification code of the specified length *@authorQ *@paramVerificationcodelength *@returnString *@since2016-09-6*/ Public Static FinalString Createverificationcode (intverificationcodelength) { //all characters that are candidates for verification code can be in Chinesestring[] verificationcodearrary={"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "s", "T", "U", "V", "w", "X", "Y", "Z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; String Verificationcode= ""; Random Random=NewRandom (); //here is the core of the generated verification code, the use of a certain range of random numbers as an array of verification code subscript, loop composition We need the length of the verification code, as the page input verification, mail, SMS Verification Code verification Line for(inti=0;i<verificationcodelength;i++) {Verificationcode + =Verificationcodearrary[random.nextint (Verificationcodearrary.length)];} returnVerificationcode; }}
2: The following is the operation of the main function of 10 sets of six-bit length verification code running results of the demonstration diagram
3: summary
The core of this example and the js-change the color of the page change the core-to obtain a six-bit random number similar, all need to use the random number function to simulate the generation of six-bit random numbers after processing, the former as the verification code the latter as the color of the 16 binary six-digit representation value.
java-a simple idea for generating a specified length verification code