This article illustrates a simple method of generating JSP verification code. Share to everyone for your reference. as follows:
<%@ page contenttype= "image/jpeg" import= "java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"%> <%!
Color getrandcolor (int fc,int BC) {//The given range gets the random color Random Random = new Random ();
if (fc>255) fc=255;
if (bc>255) bc=255;
int R=fc+random.nextint (BC-FC);
int G=fc+random.nextint (BC-FC);
int B=fc+random.nextint (BC-FC);
return new Color (R,G,B);
%> <%//Settings page does not cache Response.setheader ("Pragma", "No-cache");
Response.setheader ("Cache-control", "No-cache");
Response.setdateheader ("Expires", 0);
Creates an image int width=60 in memory, height=20;
BufferedImage image = new BufferedImage (width, height, bufferedimage.type_int_rgb);
Gets the graphics context Graphics g = image.getgraphics ();
Generate Random class Random Random = new Random ();
Set Background color G.setcolor (Getrandcolor (200,250));
G.fillrect (0, 0, width, height);
Set font g.setfont (new Font ("Times New Roman", font.plain,18);
Draw a border//g.setcolor (new Color ());
G.drawrect (0,0,width-1,height-1); Randomly generated 155 lines of interference, so that the image of the authentication code is not easily detected by other programs G.setcolor (getRandcolor (160,200));
for (int i=0;i<155;i++) {int x = random.nextint (width);
int y = random.nextint (height);
int xl = Random.nextint (12);
int yl = Random.nextint (12);
G.drawline (X,y,x+xl,y+yl);
//Fetch randomly generated authentication code (4 digits)//string rand = Request.getparameter ("Rand");
Rand = rand.substring (0,rand.indexof ("."));
String srand= "";
for (int i=0;i<4;i++) {String rand=string.valueof (Random.nextint (10));
Srand+=rand; Displays the authentication code to the image G.setcolor (new Color (20+random.nextint), 20+random.nextint (110));
Call functions come out of the same color, may be because the seed is too close, so can only directly generate g.DrawString (rand,13*i+6,16);
//The authentication code is deposited in session Session.setattribute ("Rand", SRand);
Image entry into force g.dispose ();
Output image to page imageio.write (image, "JPEG", Response.getoutputstream ());
Out.clear ();
out = Pagecontext.pushbody (); %>
I hope this article will help you with your JSP programming.