The verification code picture is generated dynamically by the program, each access content is random. So how to use the program to generate images dynamically, and can be displayed in the client page? The principle is very simple, for Java, we first develop a servlet, the task of this servlet is to give the client to generate a CAPTCHA image input, the sample code is as follows: Import Java.awt.color;import Java.awt.graphics;import Java.awt.image.bufferedimage;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.servletoutputstream;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Com.sun.image.codec.jpeg.jpegcodec;import Com.sun.image.codec.jpeg.jpegimageencoder;public Class Validateimgservlet extends Javax.servlet.http.HttpServlet implements Javax.servlet.Servlet ... {protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException ... {Response.setcontenttype ("image/jpeg");//Generate four-bit verification code stringbuffer SB = new StringBuffer (4); for (int i=0; i<4; i++) ... {int n = (int) (Math.random () *); Sb.append (n);} String Validatecode = sb.tostring (); The verification code is recorded in the session to facilitate user input after the validation request.getsession (). SetAttribute ("ValIdatecode ", Validatecode); Create a cached picture bufferedimage image = new BufferedImage (+, BUFFEREDIMAGE.TYPE_INT_RGB); Graphics g = image.getgraphics (); G.setcolor (Color.light_gray); G.fillrect (0, 0, 80, 25); G.setcolor (Color.Black); g.DrawString (Validatecode, 10, 20); G.dispose (); Servletoutputstream OutStream = Response.getoutputstream (); JPEGImageEncoder encoder = Jpegcodec.createjpegencoder (OutStream); Encoder.encode (image); Outstream.close (); The servlet is configured in Web. config with the following configuration information: <servlet> <description></description> <display-name> Validateimgservlet</display-name> <servlet-name>ValidateImgServlet</servlet-name> < Servlet-class>com.web.servlet.validateimgservlet</servlet-class> </servlet> <servlet-mapping > <servlet-name>ValidateImgServlet</servlet-name> <url-pattern>/validateimg.jpg</ Url-pattern> </servlet-mapping> OK, now we can use this dynamic verification code picture in the login page, login.jsp page content is as follows: <%[email protected ] Page LangUage= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
The generation of web CAPTCHA images-Java-based implementation