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" >
Below is the background code, here is a servlet, do not forget to configure the request URL in Web. xml
Import java.io.IOException; Import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.HttpServletResponse; public class Imageservlet extends HttpServlet {private static final long serialversionuid = 1L; public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexceptio n {response.setcontenttype ("image/jpeg");//Set the appropriate type, telling the browser output is the picture Response.setheader ("Pragma", "No-cache"); /Set the response header information to tell the browser not to cache this content Response.setheader ("Cache-control", "No-cache"); Response.setdateheader ("Expire", 0); Randomvalidatecode Randomvalidatecode = new Randomvalidatecode (); try {randomvalidatecode.getrandcode (request, response);//Output Picture method} catch (Exception e) {E.PR Intstacktrace (); }} public void DoPost (HttpServletRequest request, httpservletresponse response) throws SErvletexception, IOException {doget (request, response); } }
How the class generates a verification code
Import Java.awt.color;import java.awt.font;import Java.awt.graphics;import Java.awt.image.bufferedimage;import Java.util.Random; Import Javax.imageio.imageio;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import javax.servlet.http.HttpSession; public class Randomvalidatecode {public static final String Randomcodekey = "Randomvalidatecodekey";//Key placed in session Private random random = new random (); private string randstring = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//randomly generated string private int width = 80;//picture width private int height = 26;//picture high private int linesize = 40;//number of interference lines private int stringnum = 4;//randomly generated characters/* * Get fonts */ Private Font GetFont () {return new font ("Fixedsys", font.center_baseline,18); }/* * Get color */Private color getrandcolor (int fc,int BC) {if (FC > 255) FC = 255; if (BC > 255) BC = 255; int r = FC + Random.nextint (bc-fc-16); int g = FC + Random.nextint (BC-FC-14); int B = FC + Random.nextint (bc-fc-18); return new Color (R,G,B); /** * Generate random pictures */public void Getrandcode (HttpServletRequest request, HttpServletResponse respons e) {HttpSession session = Request.getsession (); The BufferedImage class is an image class with buffers, and the image class is the class that describes the image information BufferedImage image = new BufferedImage (width,height,bufferedimage. TYPE_INT_BGR); Graphics g = image.getgraphics ();//The Graphics object that produces the image object, the object can be g.fillrect (0, 0, width, height) for various drawing operations on the image; G.setfont (New Font ("Times New Roman", font.roman_baseline,18)); G.setcolor (Getrandcolor (110, 133)); Draw the interference line for (int i=0;i<=linesize;i++) {drowline (g); }//Draw random character String randomstring = ""; for (int i=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} catch (Exception e) {e.printstacktrace (); }}/* * Draw String */private string drowstring (Graphics g,string randomstring,int i) {G.setfont (GETFO NT ()); G.setcolor (New Color (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); return randomstring; }/* * Draw the interference line */private void Drowline (Graphics g) {int x = random.nextint (width); int y = random.nextint (height); int xl = Random.nextint (13); int yl = Random.nextint (15); G.drawline (x, Y, X+XL, y+yl); }/* * get random characters */Public String getrandomstring (int num) {return string.valueof (Randstring.charat (num)); }}
Java generic class generation CAPTCHA generated picture saved to local
Import Java.awt.color;import java.awt.font;import Java.awt.graphics2d;import Java.awt.image.bufferedimage;import Java.io.file;import Java.util.random;import Javax.imageio.ImageIO; The width of the public class Validatecode {/** * * * *//Captcha picture. private int width = 350; The height of the captcha picture. private int height = 100; Number of captcha characters private int codecount = 4; private int x = 0; Font height private int fontheight; private int Codey; Char[] codesequence = {' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '}; /** * Initialize Verify picture properties */public void init () {//width String strwidth = "350"; Height String strheight = "100"; Number of characters String Strcodecount = "4"; Converts the configured information into a numeric try {if (strwidth! = null && strwidth.length ()! = 0) {width = in Teger.parSeint (Strwidth); } if (strheight! = null && strheight.length ()! = 0) {height = Integer.parseint (strheigh T); } if (Strcodecount! = null && strcodecount.length ()! = 0) {Codecount = Integer.parseint (Strcodecount); }} catch (NumberFormatException e) {} x = width/(codecount + 1); Fontheight = height-2; Codey = height-4; } protected void Service () {try {//define image buffer BufferedImage buffimg = new Bufferedimag E (width, height, bufferedimage.type_int_rgb); Graphics2D g = buffimg.creategraphics (); Create a random number generator class random random = new random (); Fills the image with a white g.setcolor (color.white); G.fillrect (0, 0, width, height); To create a font, the size of the font should depend on the height of the image. Font font = new Font ("Fixedsys", Font.plain, Fontheight); //Sets the font. G.setfont (font); Draw a border. G.setcolor (Color.Black); G.drawrect (0, 0, width-1, height-1); Randomly generates 160 lines of interference so that the authentication code in the image is not easily detected by other programs. G.setcolor (Color.Black); for (int i = 0; i < i++) {int x = random.nextint (width); int y = random.nextint (height); int xl = Random.nextint (22); int yl = Random.nextint (22); G.drawline (x, y, X + xl, y + yl); }//Randomcode is used to save randomly generated verification codes so that the user can log in and verify. StringBuffer Randomcode = new StringBuffer (); int red = 0, green = 0, blue = 0; Random generation of Codecount number verification code. for (int i = 0; i < Codecount; i++) {//Get a randomly generated captcha number. String Strrand = String. ValueOf (Codesequence[random.nextint (34)]); Generates a random color component to construct a color value so that the output will have a different color value for each digit. Red = random.nextint (255); Green = Random.nextint (255); Blue = Random.nextint (255); Draws the verification code into the image with a randomly generated color. G.setcolor (New Color (red, green, blue)); g.DrawString (Strrand, (i + 1) * x, Codey); The resulting four random numbers are grouped together. Randomcode.append (Strrand); System.out.println (Strrand); }//Save the four digit verification code to the session. Imageio.write (buffimg, "JPEG", New File ("D://aa.jpeg")); Output the image to the servlet output stream. } catch (Exception e) {e.printstacktrace (); }} public static void Main (string[] args) {Validatecode s = new Validatecode (); S.init (); S.service (); }}
Java Generate verification Code _ go