js| Skills | graphics | Verification code
Call method
Principle, randomly generates a 4-digit 1000-9999 in the servlet and then writes this number to the session output a picture that has the four digits on the server side based on the number entered by the user and the value in the session.
Package com.schoolwx.util;
Import java.io.*;
Import java.util.*;
Import com.sun.image.codec.jpeg.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Import java.awt.*;
Import java.awt.image.*;
/**
* Title:getImg.java
* Description: This class is mainly implemented to randomly generate a 4-digit verification code, and write session,
* Copyright:copyright (c) 2003
* Company: Blue Star Software
* @author Falcon
* @version 1.1
*/
public class Getimg extends HttpServlet {
Private font mfont=new font ("Arial", font.plain,12);//Set Font
Process Post
public void DoPost (httpservletrequest request,httpservletresponse response)
Throws Servletexception,ioexception {
Doget (Request,response);
}
public void doget (httpservletrequest request,httpservletresponse response)
Throws Servletexception,ioexception {
Get a random number of 1000-9999
String s= "";
int intcount=0;
Intcount= (New Random ()). Nextint (9999);
if (intcount<1000) intcount+=1000;
S=intcount+ "";
Pay the value for the session.
HttpSession session=request.getsession (TRUE);
Session.setattribute ("getimg", s);
Response.setcontenttype ("Image/gif");
Servletoutputstream Out=response.getoutputstream ();
BufferedImage image=new BufferedImage (35,14,BUFFEREDIMAGE.TYPE_INT_RGB);
Graphics Gra=image.getgraphics ();
Set Background color
Gra.setcolor (Color.yellow);
Gra.fillrect (1,1,33,12);
Set Font Color
Gra.setcolor (Color.Black);
Gra.setfont (Mfont);
Output numbers
char c;
for (int i=0;i<4;i++) {
C=s.charat (i);
Gra.drawstring (c+ "", i*7+4,11); 7 is width, 11 is the top and bottom height position
}
JPEGImageEncoder Encoder=jpegcodec.createjpegencoder (out);
Encoder.encode (image);
Out.close ();
}
}