Verification code is a public automatic program that distinguishes users from computers and people. Can prevent: Malicious crack password, brush tickets, forum irrigation, effectively prevent a hacker to a particular registered users with a specific program brute force to make a continuous landing attempt, in fact, with the verification code is now a lot of web site way (such as China Merchants Bank online personal banking, Baidu community), We implemented this function in a relatively simple way. Today we use Java to implement a simple verification code program.
Code program implemented in Java
To generate a verification code:
- Define the BufferedImage object: New BufferedImage (BUFFEREDIMAGE.TYPE_INT_RGB);
- Get the Graphics object: bufferedimage.getgraphics ();
- Generate random verification code information by random
- Draw a picture with a graphics
- Record the verification code information into the session
- Output pictures using ImageIO
Verification code Check the steps:
- Get page Verification Code
- Get the verification code saved by session
- Compare Verification Codes
- Return validation Results
We create a Java Web project with the following structure:
Define a index.jsp to refresh the verification code, verify that the verification code cannot be empty, and submit the verification code:
<%@ 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 "><HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"><title>Insert Title here</title><Scripttype= "Text/javascript"> functionReload () {var Time= NewDate (). GetTime (); document.getElementById ("Image"). SRC= "<%=request.getcontextpath ()%>/servlet/imageservlet?id=" +Time ; }; functiondoIt () {varCode=document.getElementById ("Code"). Value; if(Code== NULL ||Code== "") {alert ("The verification code cannot be empty! "); return false; } Else { return true; } };</Script></Head><Body><formAction= "Servlet/loginservlet"Method= "Get"onsubmit= "return doIt ();">Verification Code:<inputtype= "text"name= "Codecheck"ID= "Code"> <imgID= "image"alt= "Enter Verification Code"src= "<%=request.getcontextpath ()%>/servlet/imageservlet" /> <ahref= "javascript:reload ();">Can't see clearly</a><BR> <inputtype= "Submit"value= "Submit"></form></Body></HTML>
Second, Imageservlet.java, used to generate the verification code picture and save the Verification code to the session:
PackageCom.huhx.servlet;ImportJava.awt.Color;ImportJava.awt.Graphics;ImportJava.awt.image.BufferedImage;Importjava.io.IOException;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;/** * @authorHuhx*/@WebServlet ("/servlet/imageservlet") Public classImageservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {bufferedimage bufferedimage=NewBufferedImage (68, 22, Bufferedimage.type_int_rgb); Graphics Graphics=Bufferedimage.getgraphics (); Color Color=NewColor (225, 230, 246); Graphics.setcolor (color); Graphics.fillrect (0, 0, 68, 22); Char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789". ToCharArray (); Random Random=NewRandom (); intLength =chars.length; StringBuffer Buffer=NewStringBuffer (); intindex; for(inti = 0; I < 4; i++) {Index=random.nextint (length); Graphics.setcolor (NewColor (Random.nextint), Random.nextint (188), Random.nextint (255))); Graphics.DrawString (Chars[index]+ "", (i * 15) + 3, 18); Buffer.append (Chars[index]); } request.getsession (). SetAttribute ("Code", buffer.tostring ()); Imageio.write (BufferedImage,"JPG", Response.getoutputstream ()); } protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }}
Third, Loginservlet.java, to receive the user's verification code to submit and verify:
PackageCom.huhx.servlet;Importjava.io.IOException;ImportJava.io.PrintWriter;Importjavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/** * @authorHuhx*/@WebServlet ("/servlet/loginservlet") Public classLoginservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {String Codecheck= Request.getparameter ("Codecheck"); String Raelcode= (String) request.getsession (). getattribute ("code"); Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out=Response.getwriter (); if(Codecheck.touppercase (). Equals (Raelcode.touppercase ())) {Out.println ("Verification Code Success!" "); } Else{out.println ("Verification Code failed!" "); } out.flush (); Out.close (); } protected voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }}
Note: Eclipse uses the @webservlet annotation method, and in other ways, the servlet needs to define the mapping relationship in Web. Xml.
Iv. the results of the operation are as follows:
Other Verification Code framework: Kaptcha, Jcaptcha, interested to pay attention to.
Java Basic----> Verification Code Usage