JSP generation Verification Code source program

Source: Internet
Author: User
Tags integer rand set background
Js| Program | Verification Code <%@ page contenttype= "Image/jpeg import=" java.awt.*,
Java.awt.image.*,java.util.*,javax.imageio.* "%>
<%
Create an image in memory
int width=60, height=20;
BufferedImage image = new BufferedImage (width, height,
BUFFEREDIMAGE.TYPE_INT_RGB);

Get Graphics context
Graphics g = image.getgraphics ();

Set Background color
G.setcolor (New Color (0xDCDCDC));
G.fillrect (0, 0, width, height);

Draw a border
G.setcolor (Color.Black);
G.drawrect (0,0,width-1,height-1);

Take a randomly generated authentication code (4 digits)
String rand = Request.getparameter ("Rand");
Rand = rand.substring (0,rand.indexof ("."));
Switch (Rand.length ())
{
Case 1:rand = "+rand"; Break
Case 2:rand = "+rand"; Break
Case 3:rand = "0" +rand; Break
Default:rand = rand.substring (0,4); Break
}

Save authentication Code in session
Session.setattribute ("Rand", Rand);

Display the authentication code in the image
G.setcolor (Color.Black);
Integer tempnumber = new Integer (rand);
String numberstr = tempnumber.tostring ();

G.setfont (New Font ("Atlantic Inline", font.plain,18));
String Str = numberstr.substring (0,1);
g.DrawString (str,8,17);

STR = numberstr.substring (1,2);
g.DrawString (str,20,15);
STR = numberstr.substring (2,3);
g.DrawString (str,35,18);

STR = numberstr.substring (3,4);
g.DrawString (str,45,15);

Randomly generated 88 interference points, so that the image of the authentication code is not easily detected by other programs
Random Random = new Random ();
for (int i=0;i<20;i++)
{
int x = random.nextint (width);
int y = random.nextint (height);
G.drawoval (x,y,0,0);
}

Image entry into force
G.dispose ();

Output image to Page
Imageio.write (Image, "JPEG", Response.getoutputstream ());
%>



Related Article

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.