JSP page verification Code demo_jsp programming

Source: Internet
Author: User
Tags constructor getcolor stub xmlns

In the Java background to generate the verification code ImageIO to the front page display, while the value of the validation code into the session used to match the user input authentication code, in user authentication using AJAX technology, without refreshing the page while the Verification code verification.

Program Structure diagram:

The main content of the Verifycodeutils program is a picture of the validation code generated by Java, and the value of the verification code, as follows:

Package utils;
Import Java.awt.Color;
Import Java.awt.Font;
Import Java.awt.Graphics2D;
Import Java.awt.image.BufferedImage;
Import Java.util.HashMap;
Import Java.util.Map;

Import Java.util.Random;

  public class Verifycodeutils {private static bufferedimage image = NULL;
  private static Random Random = new Random ();
    In some of the numbers that you define, generate a 4-bit random number public static string Getverifycode () {String str = ""; Char[] Code = new char[]{' 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 ', ' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' j ', ', ' K ', ' m ', ' n ', ' P ', ' Q ', ' R ', ' s ', ' t ', ' u ', ' V ', ' w ', ' x ', ' Y ', ' Z ', ' 2 '
    , ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '};
    Random Random = new Random ();
    for (int i = 0; i < 4; i++) {str + string.valueof (code[random.nextint (code.length)));
  return str; //Generate a CAPTCHA image public static Map getverifycode (int width, int heigth) {verifycodeutils.image = new BufferedImage (WI DTH, Heigth, Bufferedimage.type_int_rgb);
    Graphics2D g = (graphics2d) VerifyCodeUtils.image.getGraphics ();
    String Verifycode = Getverifycode ();
    Map map = new HashMap ();
    Map.put ("Verifycode", Verifycode);
    Fill the image with a white g.setcolor (color.white);
    G.fillrect (0, 0, width, heigth);
    Sets the font g.setfont (new font ("Arial", Font.Bold + Font.Italic, heigth-10)); 
    Draw a border.  
    G.setcolor (Verifycodeutils.getcolor ()); 
    G.drawrect (0, 0, width, heigth);  
    Randomly generate interference lines, so that the authentication code in the image is not easy to be detected by other programs G.setcolor (Color.Black);  
      for (int i = 0; i < i++) {int x = VerifyCodeUtils.random.nextInt (width);  
      int y = VerifyCodeUtils.random.nextInt (heigth);  
      int xl = VERIFYCODEUTILS.RANDOM.NEXTINT (5); 
      int yl = VERIFYCODEUTILS.RANDOM.NEXTINT (5);
      G.setcolor (GetColor ());  
    G.drawline (x, y, X + xl, y + yl);
    } char C;
      for (int i = 0; i < 4; i++) {c = Verifycode.charat (i);
    g.DrawString (c+ "", i*20+40, heigth-10); } map.put ("image", VerifycodeutiLs.image);
  return map;  
    ///randomization color public static color GetColor () {int red = 0, green = 0, blue = 0;  
    Produces a random color component to construct a color value, so that the color values of each digit of the output will be different.  
    Red = VerifyCodeUtils.random.nextInt (255);  
    Green = VerifyCodeUtils.random.nextInt (255); 
    Blue = VerifyCodeUtils.random.nextInt (255);
  return new Color (Red,green,blue);

 }
}

Verifycodeservlet the verifycodeutils generated verification code picture through IO into the front display, the code is as follows:

Package Servlet;
Import Java.awt.image.BufferedImage;
Import java.io.IOException;

Import Java.util.Map;
Import Javax.imageio.ImageIO;
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 Utils.


Verifycodeutils; /** * Servlet Implementation class Verifycodeservlet/@WebServlet ("/") public class Verifycodeservlet extends Httpserv

  Let {private static final long serialversionuid = 1L;
    /** * @see httpservlet#httpservlet () * * * Public verifycodeservlet () {super (); TODO auto-generated Constructor stub}/** * @see httpservlet#doget (httpservletrequest request, HTTPSERVLETRESP Onse response) */protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexcept
    Ion, IOException {response.setheader ("Expires", "1"); Response.setheader ("Cache-contrOl "," No-cache ");
    Response.setheader ("Pragma", "No-cache");
    Response.setheader ("Content-type", "image/jpeg");
    Map map = Verifycodeutils.getverifycode (223, 50); Pass the Verifycode value into the session to verify that the user entered the validation code correctly request.getsession (). setattribute ("Verifycode", Map.get ("Verifycode")
    . toString (). toUpperCase ()); 
  Through IO into the front-end display Imageio.write ((bufferedimage) map.get ("image"), "JPG", Response.getoutputstream ()); /** * @see Httpservlet#dopost (httpservletrequest request, httpservletresponse response) * * protected void DoP OST (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//TODO Auto-gene
  Rated method stub doget (request, response);

 }

}

The page JSP code is as follows:

<%@ 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" >  

JS implementation of AJAX code is as follows:

/** * */function Check_verifycode () {var xmlhttpreqverifycode = null;
  var url =document.getelementbyid ("base"). href + "/servlet/testverifycodeservlet";
  var verifycode = document.getElementById ("Verifycode"). Value;
  var tip = document.getElementById ("Tip");
  var errortip = "Input authentication code is incorrect";
  var successtip = "The input verification code is correct";
  Tip.innerhtml=errortip;
    if (Verifycode==null | | verifycode== "") {Tip.innerhtml=errortip;
  Tip.style.color = "Red"; }else{if (window.
    XMLHttpRequest) {//dom2 browser xmlhttpreqverifycode = new XMLHttpRequest (); else if (window. ActiveXObject) {//Use JSON syntax to create array var MSXML = [' MSXML2. xmlhttp.5.0 ', ' MSXML2. xmlhttp.4.0 ', ' MSXML2. xmlhttp.3.0 ', ' MSXML2.
      XMLHTTP ', ' microsoft.xmlhttp '];
        for (var i = 0; i < msxml.length i++) {try{Xmlhttpreqverifycode = new ActiveXObject (msxml[i));
    The catch (e) {}}} xmlhttpreqverifycode.open ("POST", url, True); Xmlhttpreqverifycode.setrequeStheader ("Content-type", "application/x-www-form-urlencoded"); Xmlhttpreqverifycode.onreadystatechange = function Testverifycodeservletresponse () {if ( Xmlhttpreqverifycode.readystate = 4 && (xmlhttpreqverifycode.status = 200 | | Xmlhttpreqverifycode.status = = 304)) {if (Xmlhttpreqverifycode.responsetext = 1) {tip.innerhtml = Succe
          Sstip;
        Tip.style.color = "green";
          }else if (Xmlhttpreqverifycode.responsetext = = 0) {tip.innerhtml = Errortip;
        Tip.style.color = "Red";
  }} xmlhttpreqverifycode.send ("code=" +verifycode); }//ajax Interaction function Createxmlhttprequest (xmlhttpreq) {if window.
  XMLHttpRequest) {//dom2 browser xmlhttpreq = new XMLHttpRequest (); else if (window. ActiveXObject) {//Use JSON syntax to create array var MSXML = [' MSXML2. xmlhttp.5.0 ', ' MSXML2. xmlhttp.4.0 ', ' MSXML2. xmlhttp.3.0 ', ' MSXML2.
    XMLHTTP ', ' microsoft.xmlhttp ']; for (var i = 0; i < msxml.length; i++) {try{xmlhttpreq = new ActiveXObject (Msxml[i]);
  catch (e) {}} return xmlhttpreq;

 }
}

}

Testverifycodeservlet and JS Interactive code is:

Package Servlet;
Import java.io.IOException;

Import Java.io.PrintWriter;
Import javax.servlet.ServletException;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse; /** * Servlet Implementation class Testverifycodeservlet/@WebServlet ("/testverifycodeservlet") public class Testverif

  Ycodeservlet extends HttpServlet {private static final long serialversionuid = 1L;
    /** * @see httpservlet#httpservlet () * * * Public testverifycodeservlet () {super (); TODO auto-generated Constructor stub}/** * @see httpservlet#doget (httpservletrequest request, HTTPSERVLETRESP Onse response) */protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexcept Ion, IOException {//TODO auto-generated method stub String codetrue = (string) request.getsession (). getattribut
    E ("Verifycode"); String CodeiNput = Request.getparameter ("code");
    System.out.println (Codeinput);
    Response.setcontenttype ("Text/html;charset=utf-8");
        PrintWriter out = Response.getwriter ()//print stream if (codeinput!=null) {if (Codeinput.touppercase (). Equals (Codetrue)) {
      Out.println ("1");
      }else{out.println ("0"); }}/** * @see httpservlet#dopost (httpservletrequest request, httpservletresponse response) * * * protect Ed void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//TOD
  O auto-generated Method Stub doget (request, response);

 }

}

XML code is

<?xml version= "1.0" encoding= "UTF-8"?> <web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http:// Java.sun.com/xml/ns/javaee/web-app_2_5.xsd "version=" 2.5 "> <display-name></display-name> < welcome-file-list> <welcome-file>demo.jsp</welcome-file> </welcome-file-list> <servlet > <servlet-name>VerifyCodeServlet</servlet-name> <servlet-class>servlet.verifycodeservlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>verifycodeservlet</ Servlet-name> <url-pattern>/servlet/VerifyCodeServlet</url-pattern> </servlet-mapping> < Servlet> <servlet-name>TestVerifyCodeServlet</servlet-name> <servlet-class> servlet.testverifycodeservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name> TesTverifycodeservlet</servlet-name> <url-pattern>/servlet/TestVerifyCodeServlet</url-pattern>
 </servlet-mapping> </web-app>

The results show:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.