In the login application, in order to prevent malicious login, the server will often need to dynamically generate the authentication code and stored in the session scope, and finally returned to the client image form to display
The following code implements the function: Write a JSP page, dynamically generate a verification code, stored in the session scope, and in the form of images returned to the client display.
Write another JSP page, referencing the code generated by this JSP page;
The authen.jsp code is as follows:
<%@ page import= "java.awt.*,java.awt.image.*,java.util.*,com.sun.image.codec.jpeg.*"%> <%!
According to the supplied AB produces a random range of color variations of the colour getcolor (int a,int b) {int n=b-a;
Random rd=new Random ();
int cr=a+rd.nextint (n);
int cg=a+rd.nextint (n);
int cb=a+rd.nextint (n);
return new Color (CR,CG,CB);
%> <%//Bottom three lines to cancel the function of the client browser cache verification Code Response.setheader ("Pragma", "No-cache");
Response.setheader ("Cache-control", "No-cache");
Response.setdateheader ("Expires", 0);
int width=60, height=20;
Generate an image in memory bufferedimage image = new BufferedImage (width, height, bufferedimage.type_int_rgb);
Graphics g = image.getgraphics ();
Random Random = new Random ();
G.setcolor (GetColor (200,250));
G.fillrect (0, 0, width, height);
G.setfont (New Font ("Times New Roman", font.bold,18));
G.setcolor (GetColor (160,200));
for (int i=0;i<160;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);
} String number=string.valueof (1000+random.nextint (8999));
String name=request.getparameter ("name");
Session.setattribute (Name,number);
G.setcolor (GetColor (20,130));
int x= (int) (width*0.2);
int y= (int) (height*0.8);
g.DrawString (Number,x,y);
G.dispose ();
JPEGImageEncoder Encoder=jpegcodec.createjpegencoder (Response.getoutputstream ());
Encoder.encode (image);
Out.close (); %>
Build another test.jsp page call verification code:
<%@ page contenttype= "text/html; charset=gb2312 "language=" java "import=" java.sql.* "errorpage=" "%> <!
DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
In the above two pages, there is the ability to remove client-side caching, this is because of the other browser, such as the use of the Internet Explorer Tour mode, will first put the picture in the cache, when the request will now be in the memory of the search is not already there, some words are not requested, which makes the validation code in the time of the failure, So to make the viewer not read the cached picture, you need to cancel the cache.
The above is the entire content of this article, I hope to help you learn.