Java Generate Verification Code

Source: Internet
Author: User

In order to prevent malicious users, or use the software to submit some content, you have to use a verification code to block, although this will affect the user experience, but in order to avoid some problems many sites have used a verification code; this afternoon reference to the document to get a verification code, here to share; This is a Web project, first of all, a page, Here is just a display verification code page index.jsp, using the default generated on it, the form did not commit, as follows

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >function  Refresh (obj) {        = " Imageservlet? " +math.random ();    }     </script>  

Here is the background code, here is a servlet, don't forget to configure the request URL in Web. xml

 PackageCom.wf.web;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public classImageservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L;  Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {response.setcontenttype ("Image/jpeg");//set the appropriate type to tell the browser what the output is for the pictureResponse.setheader ("Pragma", "No-cache");//Set the response header information to tell the browser not to cache this contentResponse.setheader ("Cache-control", "No-cache"); Response.setdateheader ("Expire", 0); Randomvalidatecode Randomvalidatecode=NewRandomvalidatecode (); Try{randomvalidatecode.getrandcode (request, response);//Output Image Method}Catch(Exception e) {e.printstacktrace (); }    }     Public voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }}

This class is a method of generating a verification code, as follows

 PackageCom.wf.web;ImportJava.awt.Color;ImportJava.awt.Font;ImportJava.awt.Graphics;ImportJava.awt.image.BufferedImage;ImportJava.util.Random;ImportJavax.imageio.ImageIO;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjavax.servlet.http.HttpSession; Public classRandomvalidatecode { Public Static FinalString Randomcodekey = "Randomvalidatecodekey";//The key that was placed in the session    PrivateRandom random =NewRandom (); PrivateString randstring = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//randomly generated string        Private intwidth = 80;//Picture Width    Private intHeight = 26;//Picture High    Private intLinesize = 40;//number of interference lines    Private intStringnum = 4;//randomly generated number of characters    /** Get Fonts*/    PrivateFont GetFont () {return NewFont ("Fixedsys", font.center_baseline,18); }    /** Get Color*/    PrivateColor Getrandcolor (intFcintBC) {        if(FC > 255) FC= 255; if(BC > 255) BC= 255; intr = FC + Random.nextint (bc-fc-16); intg = FC + Random.nextint (bc-fc-14); intB = fc + Random.nextint (bc-fc-18); return NewColor (R,G,B); }    /*** Generate random images*/     Public voidGetrandcode (httpservletrequest request, httpservletresponse response) {HttpSession session=request.getsession (); //The BufferedImage class is an image class with a buffer, and the image class is the class used to describe the image informationBufferedImage image =NewBufferedImage (WIDTH,HEIGHT,BUFFEREDIMAGE.TYPE_INT_BGR); Graphics g= Image.getgraphics ();//The Graphics object that produces the image object, which can be used for various drawing operations on the imageG.fillrect (0, 0, width, height); G.setfont (NewFont ("Times New Roman", font.roman_baseline,18)); G.setcolor (Getrandcolor (110, 133)); //Draw Interference Lines         for(inti=0;i<=linesize;i++) {drowline (g); }        //Draw Random charactersString randomstring = "";  for(inti=1;i<=stringnum;i++) {RandomString=drowstring (g,randomstring,i);        } session.removeattribute (Randomcodekey);        Session.setattribute (Randomcodekey, randomstring);        System.out.println (RandomString);        G.dispose (); Try{imageio.write (image,"JPEG", Response.getoutputstream ());//output the In-memory picture to the client in a flowing form}Catch(Exception e) {e.printstacktrace (); }    }    /** Draw a string*/    PrivateString drowstring (Graphics g,string randomstring,inti)        {G.setfont (GetFont ()); G.setcolor (NewColor (Random.nextint (101), Random.nextint (111), Random.nextint (121))); String Rand=string.valueof (getrandomstring (Random.nextint (Randstring.length ())); RandomString+=Rand; G.translate (Random.nextint (3), Random.nextint (3)); g.DrawString (Rand,13*i, 16); returnRandomString; }    /** Draw Interference lines*/    Private voidDrowline (Graphics g) {intx =random.nextint (width); inty =random.nextint (height); intXL = Random.nextint (13); intYL = Random.nextint (15); G.drawline (x, y, x+XL, y+yl); }    /** get random characters*/     PublicString getrandomstring (intnum) {        returnstring.valueof (Randstring.charat (num)); }}

Web. xml file

<?XML version= "1.0" encoding= "UTF-8"?><Web-appversion= "2.5"xmlns= "Http://java.sun.com/xml/ns/javaee"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  <servlet>    <Servlet-name>Imageservlet</Servlet-name>    <Servlet-class>Com.wf.web.ImageServlet</Servlet-class>  </servlet>  <servlet-mapping>    <Servlet-name>Imageservlet</Servlet-name>    <Url-pattern>/imageservlet</Url-pattern>  </servlet-mapping>  <welcome-file-list>    <Welcome-file>index.jsp</Welcome-file>  </welcome-file-list></Web-app>

That's all, the verification code is stored in the session, or the cookie is OK, but must be clear in time

Java Generate Verification Code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.