Package Com.tenlee.servlet;import Java.awt.color;import Java.awt.font;import java.awt.graphics2d;import Java.awt.image.bufferedimage;import Java.io.ioexception;import Java.util.random;import Javax.servlet.servletexception;import Javax.servlet.servletoutputstream;import Javax.servlet.http.HttpServlet; Import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Com.sun.image.codec.jpeg.jpegcodec;import com.sun.image.codec.jpeg.jpegimageencoder;/** * Servlet implementation Class Identityservlet */public class Identityservlet extends HttpServlet {private static final long serialversionuid = 1L; public static final char[] CHARS = {' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' K ' ', ' J ', ' L ', ' M ', ' N '};p ublic static random random = new random ();p ublic static String getrandomstring () {StringBuffer buf fer = new StringBuffer (); for (int i = 0; i < 6; i++) {Buffer.append (Chars[random.nextint (chars.length)]);} return buffer. toString ();} public static color Getrandomcolor () {//Get random color return new color (Random.nextint (255), Random.nextint (255), Random.nextint (255));} public static color Getreversecolor (color c) {//Returns a color inverse return new color (255-c.getred (), 255-c.getgreen (), 255-C.GETBL UE ());} Public Identityservlet () {super (); }protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Response.setcontenttype ("Image/jpeg"); Set the output type string randomstring = Getrandomstring ();//random string Request.getsession (True). SetAttribute ("RandomString", randomstring); int width = 100;int height = 30; Picture width and height color color = getrandomcolor (); Gets the random color used for the background color reverse = getreversecolor (color);//Inverse color, used for money foreground bufferedimage bi = new BufferedImage (width, height, BUFFEREDIMAGE.TYPE_INT_RGB); Common one color picture graphics2d g = bi.creategraphics (); Gets the drawing object G.setfont (New Font (Font.sans_serif, Font.Bold, 16)); Sets the font g.setcolor (color);//sets the font color g.fillrect (0, 0, width, height);//Draw Background G.setColor (reverse);//Set g.DrawString (RandomString, +), for (int i = 0, n = random.nextint (), i < n; i++) {//Draw up to 100 noise Point G.drawrect (Random.nextint (width), random.nextint (height), 1, 1);//random noise point}servletoutputstream out = Response.getoutputstream (); Convert to JPEG format JPEGImageEncoder encoder = Jpegcodec.createjpegencoder (out);//encoder Encoder.encode (BI); Encode the image Out.flush ();//clear cache, that is, output to client}protected void DoPost (HttpServletRequest request, httpservletresponse response) Throws Servletexception, IOException {}}
JAVA servlet Implementation Verification code