1 Verification code generation class Randomcode
Randomcode is a tool class for generating verification codes, which supports both English and digital verification codes, including English case and array, where English I, O and number 0 and 1 are not included in the generated verification code because they are prone to confusion. Randomcode supports output jpg/bmp/png/gif image format verification code.
/** * Randomcode Verification codes can be generated by static methods and instance methods. * * Static Method: * *//Generate random verification code of length 4 * String code = randomcode.randomstring (4); * *//To input the CAPTCHA image into the response output stream *//Picture format jpg * OutputStream OS = Response.getoutputstream (); * Randomcode.write (code, +, OS, "JPG"); * * Example Method: * *//Instantiation Verification Code class * Randomcode rc = new Randomcode (4); * *//To input the CAPTCHA image into the response output stream *//Picture format jpg * OutputStream OS = Response.getoutputstream (); * Rc.write (+, OS, "JPG"); * *//Get Verification Code String * String code = Rc.getcode (); * */public class Randomcode {/** * random captcha character */private static String base = "Abcdefghijkmnpqrstuvwxyzabcdefghjklmnpqrstuvwxy Z23456789 ";/** * Random Verification code length */private int length = 4;/** * Captcha string */private string code;/** * 4-bit random verification Code */public Randomcode () {T His.code = randomcode.randomstring (this.length);} public randomcode (int length) {if (length > 0) {this.length = length;} This.code = randomcode.randomstring (this.length);} /** * Generate captcha Picture * @param width picture height * @param height picture altitude * @return */public bufferedimage toimage (int width, intHeight) {return randomcode.toimage (this.code, width, height);} /** * Output Verification code picture, default image format JPEG * @param width * @param height * @param os * @throws ioexception */public void Write (int width, I NT height, OutputStream os) throws Ioexception{randomcode.write (code, width, height, os, "JPEG");} /** * Output CAPTCHA image * @param width * @param height * @param os * @param format Picture format, support jpg/jpeg/bmp/gif/png * @throws IOException */public void Write (int width, int height, outputstream os, String format) throws Ioexception{randomcode.write (code, Widt h, height, OS, format);} public int GetLength () {return length;} Public String GetCode () {return code;} /** * Static method * generates random strings * @param length string lengths * @return Random string */public static string randomstring (int length) {Random random = New Random (); StringBuffer sb = new StringBuffer (), for (int i = 0; i < length; i++) {Sb.append (Base.charat (Random.nextint (Base.length ( ))));} return sb.tostring ();} /** * static method * Output CAPTCHA image * @param code CAPTCHA String * @param width picture width * @param height picture altitude * @parAm OS picture output stream * @param format picture, support Jpg/jpeg/bmp/gif/png * @throws ioexception */public static void Write (String code, int width, int height, outputstream os, String format) throws Ioexception{bufferedimage image = Toimage (code, width, height); Mageio.write (image, format, OS);} /** * static method * Output CAPTCHA picture, default image format JPEG * @param code CAPTCHA String * @param width picture width * @param height picture height * @param os picture output stream * @throws IOException */public static void Write (String code, int width, int height, outputstream os) throws Ioexception{write (code, width, height, os, "JPEG");} /** * Static method * String to verify code picture * @param code Verification Code String * @param width captcha picture breadth, per pixel * @param height verification code picture height, per pixel * @return */public s Tatic bufferedimage toimage (String code, int width, int height) {//font size int fontSize = (int) math.ceil (height * 0.9); if (FontS Ize <) {fontSize = 20;} The position of the font on the y coordinate is int positiony = (int) math.ceil (height * 0.8); int lencode = Code.length ();//Calculate font width int fontwidth = width/(lenc Ode + 2); BufferedImage image = new BufferedImage (width,Height, bufferedimage.type_int_bgr); Graphics g = image.getgraphics ();//Picture background random color G.setcolor (Randomcolor (New Random (), (), ()) g.fillrect (0, 0, width, height);//Set the font g.setfont (new Font ("Times New Roman", Font.Bold, FontSize));//Draw Criss-cross lines on the picture to achieve a confusing effect drawlines (g, Width, height);//Draw Verification Code drawstring (g, Code, Fontwidth, Positiony) on the picture; G.dispose (); return image;} /** * Static method * In the picture of the word seat * @param g * @param code CAPTCHA String * @param fontwidth font width * @param positiony font y-coordinate */private static voi D DrawString (Graphics G, String code, int fontwidth, int positiony) {int len = code.length (); Random random = new random (), for (int i = 0; i < len; i++) {G.setcolor (Randomcolor (random)); g.DrawString (String.valueof ( Code.charat (i)), (i + 1) * fontwidth, Positiony);}} private static Color Randomcolor (random random) {int r = random.nextint (255); int g = Random.nextint (255); int b = Random.nextint (255); return new Color (R, G, b); }private static Color Randomcolor (random random, int FC, int BC) { if (FC > 255) {fc = 255; } if (BC > 255) {BC = 255; } int diff = bc-fc; int r = FC + Random.nextint (diff); int g = FC + Random.nextint (diff); int B = FC + Random.nextint (diff); return new Color (R,G,B); }/** * Static method * Draw criss-Cross lines * @param g * @param width Verification code picture Width * @param height captcha picture height */private static void DrawLines (Graphics g , int width, int height) {Random random = new random ();//number of lines int count = ((int) (Math.ceil (random.nextdouble () * 100)) + 10 0;for (int i = 0; i < count; i++) {int FC = + (int) Math.ceil (random.nextdouble () * +); int BC = + (int) Math.ceil ( Random.nextdouble () * 55); G.setcolor (Randomcolor (random, FC, BC)); int x = Random.nextint (width); int y = random.nextint (height); int xl = Random.nextint (WIDTH/5); int yl = Random.nextint (HEIGHT/5); G.drawline (x, y, X + xl, y + yl);} }}
2 servlet return Verification code
Request Path http://< Web site path >/random/code/servlet
@WebServlet ("/random/code/servlet") public class Randomcodeservlet extends HttpServlet {private static final long Serialversionuid = 1l;protected void Service (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {///Captcha picture width, unit pixel int width = 120;//captcha picture height, Unit pixel int height = 30;//captcha picture format, string format = "pn g ";//verify code character length int len = 4;//Set Picture format response.setcontenttype (" image/"+ format);//disable browser cache picture Response.setheader (" Pragma "," No-cache "), Response.setheader (" Cache-control "," No-cache "); Response.setdateheader (" Expires ", 0); String code = randomcode.randomstring (len);//output the picture to the response output stream Randomcode.write (code, width, height, Response.getoutputstream (), format);}}
3 Strust2 return Verification code
public class Randomcodeaction extends Actionsupport {private static final long Serialversionuid = -7515645222798283236l;/ * * Get Verification code */public void Generatecode () {HttpServletResponse response = Servletactioncontext.getresponse ();//Captcha picture width, unit pixel int width = 120;//captcha picture height, Unit pixel int height = 30;//captcha Picture format string formatted = "PNG";//captcha character length int len = 4;//Set Picture format response . setContentType ("image/" + format);//Disallow browser caching of picture Response.setheader ("Pragma", "No-cache"); Response.setheader (" Cache-control "," No-cache "); Response.setdateheader (" Expires ", 0); String code = randomcode.randomstring (len);//output the picture to the response output stream try {randomcode.write (code, width, height, Response.getoutputstream (), format);} catch (IOException e) {e.printstacktrace ();}}}
Verification Code configuration for STRUTS2
<package name= "Pkg-random-code" namespace= "/" extends= "Struts-default" ><action name= "randomCode_*" method= "{1}" class= "Com.rhui.web.action.RandomCodeAction" ></action></package>
Request Path http://< Web site path >/randomcode_generatecode.do
4 SPRINGMVC return Verification code
Request Path http://< Web site path >/random/code/generate.do
Package Com.rhui.web.controller;import Java.io.ioexception;import Javax.servlet.http.httpservletresponse;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Com.rhui.util.RandomCode, @Controller @requestmapping ("/random/code") public class Randomcodecontroller {@ Requestmapping ("/generate.do") public void Generatecode (HttpServletResponse response) {//Captcha picture width, unit pixel int width = 120;/ /captcha picture height, Unit pixel int height = 30;//captcha Picture format string formatted = "PNG";//captcha character length int len = 4;//Set Picture format Response.setcontenttype ("Imag e/"+ format);//disable browser cache picture Response.setheader (" Pragma "," No-cache "); Response.setheader (" Cache-control "," No-cache "); Response.setdateheader ("Expires", 0); String code = randomcode.randomstring (len);//output the picture to the response output stream try {randomcode.write (code, width, height, Response.getoutputstream (), format);} catch (IOException e) {e.printstacktrace ();}}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Web authentication Code