Javaweb Generate picture Verification code __java base

Source: Internet
Author: User
Tags border color rand set background

Do a login page, add picture Verification Code, need page, action jump, Struts.xml transmission image data, randomly generated classes, and the use of random characters to generate pictures of the class.

The rest is when the page is logged in, the picture is generated and the data checksum is matched.


Validatecode.java

Import Java.util.Arrays;
    
    No, simple contains only numbers, Medium contains numbers and lowercase English, Hard contains both numbers and uppercase English/public enum Securitycodelevel {Simple,medium,hard}; /** * Generates default verification code, 4-bit medium difficulty * @return String Verification Code */public static string Getsecuritycode () {return GE
    Tsecuritycode (4,securitycodelevel.medium,false); /** * The length and difficulty of any verification code * @param length * @param level difficulty levels * @param iscanrepeat Whether it can appear heavy The complex character, if true, may appear as 5578 so contains two 5, if false, this situation cannot occur * @return String Verification Code/public static String getsecurity
        
        Code (int length,securitycodelevel Level,boolean iscanrepeat) {//randomly extract len character int len=length;
                      Character Set combination (excluding the confusing number 0, number 1, letter L, letter O, Letter 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 ', ' F ' , ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z '
        
        };
        Intercepts the character array if (level==securitycodelevel.simple) {Codes=arrays.copyofrange (codes, 0,9) according to different difficulty;
        }else if (level==securitycodelevel.medium) {Codes=arrays.copyofrange (codes, 0,33);
        
        }//Character set combined with length int n=codes.length; Throw runtime exception if (Len>n&&iscanrepeat==false) {throw new RuntimeException (St Ring.format ("Call Securitycode.getsecuritycode (%1$s,%2$s,%3$s) exception," + "when Iscanrepeat is%3$s
        , the incoming parameter%1 $ s cannot be greater than%4$s ", len,level,iscanrepeat,n));
        
        }//Storage of extracted characters char[] result=new Char[len]; To determine if there is a duplicate character IF (iscanrepeat) {for (int i=0;i<result.length;i++) {//index 0 and n-1 int r= (int
            
                ) (Math.random () *n);
            Setting the first element in result to Codes[r] the value result[i]=codes[r]; }}else{for (int i=0;i<result.length;i++) {//index 0 and N-1 int r= (in
                
                T) (Math.random () *n);
                
                Setting the first element in result to Codes[r] the value result[i]=codes[r];
                You must make sure that the character is not extracted again because all extracted characters must be different.
                Thus, the last character in the array is rewritten codes[r] and n is reduced by 1 codes[r]=codes[n-1];
            n--;
    } return string.valueof (result); }
}

Validateimg.java

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.JPEGCodec;

Import Com.sun.image.codec.jpeg.JPEGImageEncoder; * @param securitycode Verification Code character * @return BufferedImage picture/public static BufferedImage CreateImage (S
        Tring Securitycode) {//Verification code length int codelength=securitycode.length ();
        Font size int fsize = 15;
        int fwidth = fsize + 1;
        Picture width int width = codelength * fwidth + 6;
        
        Picture height int height = fsize * 2 + 1; Picture BufferedImage image=new bufferedimage (width, height, bufferedimage.
        TYPE_INT_RGB);
        
        Graphics G=image.creategraphics ();
        Set Background color g.setcolor (color.white);
        
        Fill 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 Border G.drawrect (0, 0, width-1, height-1);
        Draw the noise point Random rand = new Random ();
        Set the noise-point 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 the 1*1 size of the rectangular g.drawrect (x, Y, 1, 1);  
        }//Draw verification Code int codey = HEIGHT-10;
        Sets 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 * + 5, Codey);
        
        //Close resource g.dispose ();
    return image; /** * Returns the stream format of the captcha image * @param securitycode Verification Code * @return Bytearrayinputstream Picture Stream * * Publ IC Static Bytearrayinputstream Getimageasinputstream (String securitycode) {bufferedimage image = Createim
        Age (Securitycode);
    return Convertimagetostream (image);
     /** * Convert BufferedImage to Bytearrayinputstream * @param image Image * @return Bytearrayinputstream stream * * private static Bytearrayinputstream Convertimagetostream (bufferedimage image) {bytearrayinput
        Stream inputstream = null;
        Bytearrayoutputstream BOS = new Bytearrayoutputstream ();
        JPEGImageEncoder JPEG = jpegcodec.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; }
}

Validateaction.action

Import Java.io.ByteArrayInputStream;

Import Java.util.Map;

Import Org.apache.struts2.interceptor.SessionAware;

Import Com.opensymphony.xwork2.ActionSupport; The session private sessionaware{of the MAP type in the public class Validaction extends Actionsupport implements//struts2 map<string,
	Object> session;
	
	Picture Stream private Bytearrayinputstream imagestream; Public String Valid () {<span style= "White-space:pre" > </span>//if you turn on hard mode, you can be case-insensitive <span style= " White-space:pre "> </span>//String securitycode = Validatecode.getsecuritycode (4,securitycodelevel.hard,
      
      False). toLowerCase ();
      Gets the default difficulty and length verification code String Securitycode = Validatecode.getsecuritycode ();
      ImageStream = Validateimg.getimageasinputstream (Securitycode);
      Put in session session.put ("Session_security_code", Securitycode);
	return SUCCESS;
		
	} public void Setsession (map<string, object> sessions) {this.session = session; } public Bytearrayinputstream GetimagestrEAM () {return imagestream;
	public void Setimagestream (Bytearrayinputstream imagestream) {this.imagestream = ImageStream;
	Public map<string, Object> getsession () {return session;
 }

}
Struts.xml

<action name= "valid" class= "com.web.action.ValidAction" method= "valid" > <result name= "Success" Type= "
		Stream ">
	            <param name=" ContentType ">image/jpeg</param>
	            <param name=" InputName "> imagestream</param>
	            <param name= "buffersize" >2048</param>
        	</result>
</ Action>

login.jsp

<pre name= "code" class= "HTML" ><script language= "JavaScript" type= "Text/javascript" >
function Changeimage () {
<span style= "White-space:pre" >	</span>var rom = parseint (100000000000* Math.random ());
<span style= "White-space:pre" >	</span>document.getelementbyid ("Imagevalid"). src= "<%=basePath %>valid.action?timestamp= "+rom;
}
Window.onload=function () {
<span style= "White-space:pre" >	</span>var rom = parseint ( 100000000000*math.random ());
<span style= "White-space:pre" >	</span>document.getelementbyid ("UserName"). focus ();
<span style= "White-space:pre" >	</span>document.getelementbyid ("Imagevalid"). src= "<%= Basepath%>valid.action?timestamp= "+rom;
<span style= "White-space:pre" >	</span>$ ("#fbl"). Val (document.documentElement.clientHeight);

</script>
<input  name= "valid" id= "Validnum" maxlength= "4" class= "Loginimgnum"/><span> </span>





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.