1. Create a new dynamic WEB Project project with Eclipse tools as follows:
2. Create a new package under the SRC directory of Java resources with the package name Com.it666.code
3. Create 2 Servlets under the Com.it666.code package, named Checkcodeservelt, Registservlet, respectively
Checkcodeservelt Code:
PackageCom.it666.code;importJava.awt.color;importJava.awt.font;importJava.awt.graphics;importJava.awt.graphics2d;importJava.awt.image.bufferedimage;importJava.io.bufferedreader;importJava.io.filereader;importJava.io.ioexception;importJava.util.arraylist;importJava.util.list;importJava.util.random;importJavax.imageio.imageio;importJavax.servlet.servletexception;importJavax.servlet.annotation.webservlet;importJavax.servlet.http.httpservlet;importJavax.servlet.http.httpservletrequest;importJavax.servlet.http.HttpServletResponse; @WebServlet ("/checkcodeservlet")) public class Checkcodeservlet extendsHttpServlet {private static final long Serialversionuid = 1L; Save all idioms in collection private list<string> words = new arraylist<string>(); @Override public void init () throwsservletexception {///initialization phase, read New_words.txt//Web project read file, must use absolute disk path of String path = Getservletcontext (). Getrealpath ("/ Web-inf/words.txt "); Try{BufferedReader reader = new BufferedReader (newFileReader (path)); String Line; Add all the read idioms to a set while (line = Reader.readline ()) = null) {Words.add (line);} reader.close (); } catch(IOException e) {E.printstacktrace ();} } public voidDoget (HttpServletRequest request, httpservletresponse response) throwsServletexception, IOException {int width = 120; int height = 30; Step one draw a picture in memory bufferedimage bufferedimage = newBufferedImage (width, height, bufferedimage.type_int_rgb); Step two picture draw background color---by drawing object graphics graphics = Bufferedimage.getgraphics ();//drawing Object---brush//Draw any graphic before you must specify a color graphics. SetColor (Getrandcolor (200, 250)); Graphics.fillrect (0, 0, width, height); Step three Draw BorderGraphics.setcolor (Color.White); Graphics.drawrect (0, 0, width-1, height-1); Step 44 Random Numbers graphics2d graphics2d =(graphics2d) graphics; Set the output font graphics2d.setfont (new font ("Arial", Font.Bold, 18)); Random random = new random ();//Generate stochastic number int index =Random.nextint (Words.size ()); String Word = words.get (index);//Get idiomSYSTEM.OUT.PRINTLN (word); define x coordinate int x = 10; for (int i = 0; i < word.length (); i++) {//Random color Graphics2d.setcolor (new color (+ random.nextint (110), 20 +Random. Nextint (+), + random.nextint (110))); Rotate -30---30 degrees int jiaodu = Random.nextint (60)-30; Conversion Radian Double theta = Jiaodu * math.pi/180; Get the alpha-numeric char c =Word.charat (i); Output C to Picture Graphics2d.rotate (Theta, X, 20); Graphics2d.drawstring (String.valueof (c), X, 20); Graphics2d.rotate (-theta, X, 20); x + = 30; }//Save the CAPTCHA content session (for enterprise Development)//request.getsession (). SetAttribute ("checkcode_session", word); The generated verification code is stored in the global domain object (typically not in this way) This.getservletcontext (). SetAttribute ("Checkcode", word); Step five draw the interference line Graphics.setcolor (Getrandcolor (160, 200)); IntX1; IntX2; IntY1; Inty2; for (int i = 0; i <; i++) {x1 =Random.nextint (width); x2 = Random.nextint (12); Y1 = random.nextint (height), y2 = Random.nextint (), Graphics.drawline (x1, y1, x1 + x2, x2 + y2);}// Output the above image to the browser ImageIO graphics.dispose ();//Release the resource//write the picture to Response.getoutputstream () Imageio.write (bufferedimage, "JPG" , Response.getoutputstream ()); } public void doPost (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException {doget (request, response);}/** * takes a range of color * * @param FC * int Range parameter 1 * @param BC * INT Range Parameter 2 * @return C Olor */Private color getrandcolor (int fc, int BC) {//take its random colors random random = new random (); if (FC > 255) {FC = 255 ;} if (BC > 255 ) {BC = 255 ;} int r = FC + random.nextint (BC- FC); int g = f C + random.nextint (BC- FC), int b = fc + random.nextint (BC- FC), return new Color (R, G, b);}
The Registservlet code is as follows:
PackageCom.it666.code;importJava.io.ioexception;importJavax.servlet.servletexception;importJavax.servlet.annotation.webservlet;importJavax.servlet.http.httpservlet;importJavax.servlet.http.httpservletrequest;importJavax.servlet.http.HttpServletResponse; @WebServlet ("/registservelt")) public class Registservelt extendsHttpServlet {private static final long Serialversionuid = 1L; protected void Service (HttpServletRequest request, httpservletresponse response) throws Servletexception , IOException {//Receive the contents of the request parameter String code = request.getparameter ("code" ); SYSTEM.OUT.PRINTLN (code); Transcode the requested parameter content from iso8859-1 to UTF-8 byte[] bytes = code.getbytes ("iso8859-1" ); code = new String (bytes, "UTF-8" ); System.out.println ("code=" + code);//Get Authenticode content String name = (string) this.getservletcontext (). getattribute (" Checkcode "); System.out.println ("name=" + name);//Set the encoding used in the buffer//response.setcharacterencoding ("UTF-8");//Set the encoding used in the buffer, Tells the browser what character set to use to receive the response Response.setcontenttype ("Text/html;charset=utf-8" );//to match and output the matching result if (Name.equals ( Code) {Response.getwriter (). Write ("Authenticode correct" );} else {response.getwriter (). Write ("Authenticode error" ); Response.setheader ("Refresh", "3;url=/26-servlet/code.html ")}}}
4. Create the Web. XML, words.txt under the Web-inf folder of the WebContent folder.
The Web. XML code reads as follows:
<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "metadata-complete=" false "version=" 3.0 "> < absolute-ordering/> <display-name>web</display-name> <welcome-file-list> < welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
The Words.txt file is mainly used to put the text of the verification code. As follows:
5. Create only code.html files under the WebContent folder (no other files are created)
Code.html Code:
<! DOCTYPE html> chang (obj) { "/26-servlet/checkcodeservlet?time=+ new Date (). GetTime ();} </script>
6. Stand-alone operation under the code.html file
The following is the Eclipse tool test Result:
1. Match the correct instance:
2. Matching Error instances:
From zero to Javaweb series 7web Server-----User Login Interface Two-dimensional code production