public class Authimg extends HttpServlet {
/**
*
*/
Private static final long serialversionuid = 4975974534946437434L;
Set the font and size of the graphics Captcha string
Private font mfont = new Font ("Microsoft Jas Black", Font.Italic, 18);
Private random random = new random ();
public void Init () throws Servletexception {
Super.init ();
}
Service methods for generating server responses
public void Service (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
Prevents generated pages from being cached, ensuring that new codes are generated every time
Response.setheader ("Pragma", "No-cache");
Response.setheader ("Cache-control", "No-cache");
Response.setdateheader ("Expires", 0);
Response.setcontenttype ("Image/jpeg");
Specify the size of the CAPTCHA picture
int width = N, height = 24;
Create a new picture
BufferedImage image = new BufferedImage (width, height, bufferedimage.type_3byte_bgr);
Draw content in a picture
Graphics g = image.getgraphics ();
G.setcolor (New Color (252, 252, 252));
G.fillrect (1, 1, width, height);
G.setcolor (New Color (252, 252, 252));
G.drawrect (0, 0, width, height);
G.setfont (Mfont);
G.setcolor (New Color (252, 252, 252));
This variable is used to save the system-generated random variable string
String SRand = "";
int Colorr = Random.nextint (200);
int colorg = Random.nextint (200);
int colorb = Random.nextint (200);
for (int i = 0; i < 4; i++) {
Get a random string
String tmp = Getrandomchar ();
SRand + = tmp;
Add a system-generated random string to the picture
G.setcolor (New Color (Colorr, colorg, Colorb));
g.DrawString (TMP, * i + 10, 20);
}
Get the user's session
HttpSession session = Request.getsession (true);
Add the system generated random verification code to the user session
Session.setattribute ("Rand", SRand);
G.dispose ();
Output Verification Code picture
Imageio.write (Image, "JPEG", Response.getoutputstream ());
}
Methods for generating random strings
Private String Getrandomchar () {
int itmp = Random.nextint (10);
Return string.valueof (ITMP);
}
}
Java Generate CAPTCHA Image