This week, we have completed a small function, that is, the verification code used during login. The following describes the steps.
Step 1: generate a random Verification Code
Package COM. dong. framework. tool; import Java. util. arrays;/*** tool class to generate a Random verification code string * @ version 1.0 2012/08/21 * @ author dongliyang **/public class securitycode {/*** Verification Code difficulty level, simple only contains numbers. Medium contains numbers and lower-case English letters. Hard contains numbers and upper-case English letters */Public Enum securitycodelevel {simple, medium, hard};/*** generates the default verification code, 4-digit moderate difficulty * @ return string Verification Code */public static string getsecuritycode () {return getsecuritycode (4, securitycodelevel. me Dium, false);}/*** a verification code with arbitrary length and difficulty * @ Param length * @ Param level difficulty level * @ Param iscanrepeat indicates whether repeated characters can appear, if the value is true, 5578 may contain two 5 S. If the value is false, this problem cannot occur * @ return string Verification Code */public static string getsecuritycode (INT length, securitycodelevel level, boolean iscanrepeat) {// random extraction of Len characters int Len = length; // Character Set combination (except for confusing numbers 0, numbers 1, letters l, letters O, and letters O) char [] codes = {'1', '2', '3', '4', '5', '6', '7', '8 ', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'h', 'I', 'J', 'k', 'M', 'n', 'P ', 'Q', 'R', 's', 't', 'U', 'V', 'w', 'x', 'y', 'z ', 'A', 'B', 'C', 'D', 'E', 'E', 'F', 'G', 'h', 'I', 'J ', 'k', 'l', 'M', 'n', 'P', 'Q', 'R', 's', 't', 'U ', 'V', 'w', 'x', 'y', 'z'}; // truncates the character array if (Level = securitycodelevel. simple) {Codes = arrays. copyofrange (codes, 0, 9);} else if (Level = securitycodelevel. medium) {Codes = arrays. copyofrange (codes,);} // Character Set combination length int n = codes. length; // throw runtime exception If (LEN> N & iscanrepeat = false) {Throw new runtimeexception (string. format ("Call securitycode. getsecuritycode (% 1 $ S, % 2 $ S, % 3 $ s) has an exception. "+" When iscanrepeat is % 3 $ s, the input parameter % 1 $ s cannot be greater than % 4 $ s ", Len, level, iscanrepeat, n ));} // store the extracted characters char [] result = new char [Len]; // judge whether repeated characters can appear if (iscanrepeat) {for (INT I = 0; I <result. length; I ++) {// index 0 and n-1 int r = (INT) (math. random () * n); // set the I-th element in the result to the value stored in codes [R]. Result [I] = codes [R] ;}} Else {for (INT I = 0; I <result. length; I ++) {// index 0 and n-1 int r = (INT) (math. random () * n); // set the I element in the result to the value stored in codes [R]. Result [I] = codes [R]; // make sure that the character is not extracted again, because all extracted characters must be different. // Therefore, use the last character in the array to rewrite codes [R], and subtract n from 1 codes [R] = codes [n-1]; n -- ;}} return string. valueof (result );}}
Step 2: generate an image
Package COM. dong. framework. tool; import Java. AWT. color; import Java. AWT. font; import Java. AWT. graphics; import Java. AWT. image. bufferedimage; import Java. io. bytearrayinputstream; import Java. io. bytearrayoutputstream; import Java. io. ioexception; import Java. util. random; import com.sun.image.codec.jpeg. imageformatexception; import com.sun.image.codec.jpeg. export codec; import com.sun.image.codec.jpeg. required imageencoder;/*** tool class, generate Verification Code image * @ version 1.0 2012/08/21 * @ author dongliyang **/public class securityimage {/*** generate Verification Code image * @ Param securitycode Verification Code character * @ return bufferedimage image */Public static bufferedimage createimage (string securitycode) {// verification code length int codelength = securitycode. length (); // font size int fsize = 15; int fwidth = fsize + 1; // Image Width int width = codelength * fwidth + 6; // Image Height int Height = fsize * 2 + 1; // image bufferedimage image = new bufferedimage (width, height, bufferedimage. type_int_rgb); graphics G = image. creategraphics (); // sets the background color G. setcolor (color. white); // fill in the background G. fillrect (0, 0, width, height); // sets the border color G. setcolor (color. light_gray); // border font style G. setfont (new font ("Arial", Font. bold, height-2); // draw the border G. drawrect (0, 0, width-1, height-1); // draw the noise random Rand = new random (); // set the noise color G. setcolor (color. light_gray); For (INT I = 0; I <codelength * 6; I ++) {int x = Rand. nextint (width); int y = Rand. nextint (height); // draw a 1*1 rectangle G. drawrect (X, Y, 1, 1);} // draw the verification code int Codey = height-10; // set the font color and style G. setcolor (new color (19,148,246); G. setfont (new font ("Georgia", Font. bold, fsize); For (INT I = 0; I <codelength; I ++) {G. drawstring (string. valueof (securitycode. charat (I), I * 16 + 5, Codey);} // close resource G. dispose (); Return image;}/*** return the stream format of the Verification Code image * @ Param securitycode Verification Code * @ return bytearrayinputstream image stream */public static bytearrayinputstream getimageasinputstream (string securitycode) {bufferedimage image = createimage (securitycode); Return convertimagetostream (image );} /*** convert bufferedimage to bytes * @ Param image * @ return bytearrayinputstream stream */Private Static bytearrayinputstream convertimagetostream (bufferedimage image) {bytearrayinputstream inputstream = NULL; bytearrayoutputstream Bos = new bytearrayoutputstream (); required imageencoder JPEG = required codec. createjpegencoder (BOS); try {JPEG. encode (image); byte [] BTS = Bos. tobytearray (); inputstream = new bytearrayinputstream (BTS);} catch (imageformatexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();} return inputstream ;}}
Step 3: Combine the verification code with Struts 2
Package COM. dong. security. action; import COM. opensymphony. xwork2.actionsupport; import Java. io. bytearrayinputstream; import Java. util. map; import Org. apache. struts2.interceptor. sessionaware; import COM. dong. framework. tool. securitycode; import COM. dong. framework. tool. securityimage;/*** provides the image Verification Code * @ version 1.0 2012/08/22 * @ author dongliyang */@ suppresswarnings ("serial ") public class securitycodeimageaction extends actionsupport implements sessionaware {// map-type session private map in struts2 <string, Object> session; // picture stream private bytearrayinputstream imagestream; Public bytearrayinputstream getimagestream () {return imagestream;} public void setimagestream (bytearrayinputstream imagestream) {This. imagestream = imagestream;} Public String execute () throws exception {// if hard mode is enabled, it can be case-insensitive. // string securitycode = securitycode. getsecuritycode (4, securitycodelevel. hard, false ). tolowercase (); // obtain the default difficulty and length verification code string securitycode = securitycode. getsecuritycode (); imagestream = securityimage. getimageasinputstream (securitycode); // put it into the session. put ("session_security_code", securitycode); Return success;} public void setsession (Map <string, Object> session) {This. session = session ;}}
Step 4: Configure struts. xml
<package name="Security" namespace="/Security" extends="struts2"> <action name="SecurityCodeImageAction" class="com.dong.security.action.SecurityCodeImageAction"> <result name="success" type="stream"> <param name="contentType">image/jpeg</param> <param name="inputName">imageStream</param> <param name="bufferSize">2048</param> </result> </action> </package>
Step 5: front-end JSP and JS
<SCRIPT type = "text/JavaScript"> function changevalidatecode (OBJ) {// obtain the current time as a parameter, without specific significance var timenow = new date (). gettime (); // each request requires a different parameter. Otherwise, the same verification code may be returned. // This is related to the browser's cache mechanism. You can also set the page to not be cached, in this way, this parameter is not used. OBJ. src = "securitycodeimageaction? D = "+ timenow ;}</SCRIPT>
<input type =" text "name =" securitycode "/>
This is the entire process of generating the verification code!