Java Basic----> Verification Code Usage

Source: Internet
Author: User

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:

    1. Define the BufferedImage object: New BufferedImage (BUFFEREDIMAGE.TYPE_INT_RGB);
    2. Get the Graphics object: bufferedimage.getgraphics ();
    3. Generate random verification code information by random
    4. Draw a picture with a graphics
    5. Record the verification code information into the session
    6. Output pictures using ImageIO

Verification code Check the steps:

    1. Get page Verification Code
    2. Get the verification code saved by session
    3. Compare Verification Codes
    4. 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

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.