Java implementation Verification code generation and validation

Source: Internet
Author: User
Tags add time

Transferred from: https://www.cnblogs.com/nanyangke-cjz/p/7049281.html

We all know that in order to prevent our website by some people and hackers malicious attacks, such as the registration page of our website, if we do not add a verification code box when the user registers, others can write a script to your site for malicious registration, such as every minute to your site to register n times, Then your site will be attacked and crashed. When we add the verification code, someone else must recognize your verification code when they write the script, and to identify the content in the image verification code, but it is not so easy, it can effectively prevent our website from malicious registration attack. Nonsense not much to say, directly on the code.

Tool class for generating verification codes and CAPTCHA pictures

 1 package com.utils; 2 3 Import Java.awt.Color; 4 Import Java.awt.Font; 5 Import Java.awt.Graphics; 6 Import Java.awt.image.BufferedImage; 7 Import Java.awt.image.RenderedImage; 8 Import Java.io.FileOutputStream; 9 Import java.io.outputstream;10 Import java.util.hashmap;11 import java.util.map;12 import java.util.random;13 14  Import javax.imageio.imageio;15 public class Codeutil {$ private static int width = 90;//defines the width18 private of the picture  static int height = 20;//defines the picture's height19 private static int codecount = 4;//Defines the number of verification codes displayed on the picture. private static int XX = 15;21 private static int fontheight = 18;22 private static int codey = 16;23 private static char[] Codeseq uence = {' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N ', ' O ', ' P ', ' Q ', ' R ', ' S ', ' T '      , ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z ', ' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '};25 26/**27 * Generate a map set 28 * Code for generated verification code * Codepic for generated captcha BufferedImage object 30     * @return31 */32 public static map<string,object> Generatecodeandpic () {33//definition image Buffer34 BufferedImage buffimg = new BufferedImage (width, height, bufferedimage.type_int_rgb);//graphics2d GD = Bu Ffimg.creategraphics ();//Graphics2D GD = (graphics2d) buffimg.getgraphics (); Notoginseng Graphics gd = buffimg.g Etgraphics (); 38//Create a random number generator class The random random = new random (); 40//Fill the image with white Gd.setcolor (Color.White); gd.fillrect (0, 0, width, height); 43 44//Create a font, the size of the font should be based on the height of the picture. Font font = new Font ("Fixedsys", Font.Bold, Fontheight); 46//Set fonts. Gd.setfont (font); 48 49//Draw border. Gd.setcolor (Color.Black), gd.drawrect (0, 0, width-1, height-1) 52 53//randomly generates 40 lines of interference, making the recognition in the image The code is not easily detectable by other programs. Gd.setcolor (color.black); (int i = 0; i <; i++) {~ = int x = Random.nextint (Widt h); int y = Random.nextint (height), + 60 int xl = Random.nextint (n), yl int = random.nextint (12); Gd.drawline (x, y, X + xl, y + yl),}62//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;66 67//randomly generated C Odecount The verification code of the number. (int i = 0; i < Codecount; i++) {69//Get a randomly generated captcha number. The String code = string.valueof (Codesequence[random.nextint (36))), 71//generates a random color component to construct a color value so that the output of each digit The color values will be different. Red = random.nextint (255); Random.nextint (255); blue = Random.nextint (2 55) 75 76//Use a randomly generated color to draw the verification code into the image.             Gd.setcolor (New Color (red, green, blue)), Gd.drawstring (code, (i + 1) * xx, Codey); 79 80 The resulting four random numbers are grouped together. Bayi Randomcode.append (code);}83 map<string,object> Map =new Hashmap<striNg,object> (); 84//Store CAPTCHA map.put ("code", Randomcode); 86//Store generated verification code BufferedImage object P.put ("Codepic", buffimg); return map;89}90 public static void Main (string[] args) throws Exception          {92//create file output stream object OutputStream out = new FileOutputStream ("d://img/" +system.currenttimemillis () + ". jpg"); 94 map<string,object> map = Codeutil.generatecodeandpic (), Imageio.write (renderedimage) Map.get ("Co Depic ")," JPEG ", Out), System.out.println (" The value of the CAPTCHA is: "+map.get (" Code ")); 97}98}

Next is a JSP, servlet application Demo

1.jsp page Code

 1 <%@ page language= "java" contenttype= "text/html; Charset=utf-8 "2 pageencoding=" UTF-8 "%> 3 <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > 4 

2. servlet that generates a verification code in the background

Package Com.code;import Java.awt.image.renderedimage;import Java.io.ioexception;import java.util.Map;import Javax.imageio.imageio;import Javax.servlet.servletexception;import Javax.servlet.servletoutputstream;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Javax.servlet.http.httpsession;import com.utils.codeutil;/** * servlet Implementation class Codeservlet */@WebServlet    ("/getcode") public class Codeservlet extends HttpServlet {private static final long serialversionuid = 1L; protected void Doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {//Call        Tool class generated verification code and verification Code picture map<string, object> codemap = Codeutil.generatecodeandpic ();        Save the four-digit verification code to the session.        HttpSession session = Req.getsession ();        Session.setattribute ("Code", Codemap.get ("code"). toString ());    Suppresses image caching.    Resp.setheader ("Pragma", "No-cache");        Resp.setheader ("Cache-control", "No-cache");        Resp.setdateheader ("Expires",-1);        Resp.setcontenttype ("Image/jpeg");        Output the image to the servlet output stream.        Servletoutputstream SOS;            try {SOS = Resp.getoutputstream ();            Imageio.write ((renderedimage) codemap.get ("Codepic"), "JPEG", SOS);        Sos.close ();        } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }    }}

3. servlet that verifies the verification code

Package Com.code;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import javax.servlet.http.HttpSession; @WebServlet ("/checkcode") public class Checkcode extends HttpServlet {private static fi    nal long serialversionuid = 1L; protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexcep tion {} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletex        Ception, IOException {String code = request.getparameter ("code");        Verify the captcha String Sessioncode = Request.getsession (). getattribute ("code"). toString (); if (code! = NULL &&! "). Equals (code) && Sessioncode! = NULL &&! "". Equals (Sessioncode)) {if (Code.equalsignorecase (Sessioncode) {response.getwriter (). println ("Validation passed!            "); } else {Response.getwriter (). println ("Validation failed!            "); }} else {Response.getwriter (). println ("Validation failed!        "); }    }}

Java implementation Verification code generation and validation

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.