A simple example of jquery implementation without refreshing verification code _jquery

Source: Internet
Author: User
Tags flush generator stringbuffer

1. Thinking:

The code picture on the page is a servlet, using jquery to implement the asynchronous validation information

2. Documents used

Verifycodeservlet.java-the servlet used to generate pictures

Resultservlet.java-servlet for verifying the correctness of Authenticode

Verifycode.js--Verify the JS file

Jquery.js the source file in the--jquery package

verifycode.jsp--page

3. Code

Verifycodeservlet.java

Java code

Import Java.awt.Color;  
Import Java.awt.Font;  
Import Java.awt.Graphics2D;  
Import Java.awt.image.BufferedImage;  
  
Import Java.util.Random;  
Import Javax.imageio.ImageIO;  
Import javax.servlet.ServletException;  
Import Javax.servlet.ServletOutputStream;  
Import Javax.servlet.http.HttpServlet;  
Import Javax.servlet.http.HttpServletRequest;  
Import Javax.servlet.http.HttpServletResponse;  
  
Import javax.servlet.http.HttpSession;  
  public class Verifycodeservlet extends HttpServlet {//Verify code picture width.  
  
  private int width = 60;  
  The height of the verification code picture.  
  
  private int height = 20;  
  
  Number of authentication code 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 ', ' O ', ' P ', ' Q ', ' R ',  
  
  ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z ', ' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '};  /** * Initialize validation picture properties
   */public void init () throws servletexception {//) Get initial information/width String strwidth = this from Web.xml.  
    Getinitparameter ("width");  
    Height String strheight = this.getinitparameter ("height");  
  
    Number of characters String Strcodecount = This.getinitparameter ("Codecount"); Converts the configured information to a numeric try {if (strwidth!= null && strwidth.length ()!= 0) {width = Integer.par  
      Seint (Strwidth);  
      } if (strheight!= null && strheight.length ()!= 0) {height = Integer.parseint (strheight); } if (Strcodecount!= null && strcodecount.length ()!= 0) {codecount = Integer.parseint (st  
      Rcodecount);  
    The catch (NumberFormatException e) {} x = width/(codecount + 1);  
    Fontheight = height-2;  
  
  Codey = height-4; } protected void Service (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, java.io . Ioexception {//define image buffer BufferedImage buffimg = new BufferedImage (width, height, bufferedimage.type  
    _INT_RGB);  
  
    Graphics2D g = buffimg.creategraphics ();  
  
    Create a random number generator class Random Random = new Random ();  
    Fill 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 be based on the height of the picture.  
    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 generated 160 lines of interference, so that the image of the authentication code is not easily detected by other programs.  
    G.setcolor (Color.Black);  
      for (int i = 0; i < 160 i++) {int x = random.nextint (width);  
      int y = random.nextint (height);  
      int xl = Random.nextint (12);  
      int yl = Random.nextint (12);  
    G.drawline (x, y, X + xl, y + yl);  
    The//Randomcode is used to save the randomly generated verification code so that the user can authenticate after logging in.  
    StringBuffer Randomcode = new StringBuffer (); int red = 0, Green = 0, blue = 0;  
    A validation code that randomly generates CODECOUNT numbers.  
      for (int i = 0; i < Codecount i++) {//Get a randomly generated captcha number.  
      String Strrand = string.valueof (Codesequence[random.nextint (36)]);  
      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 = random.nextint (255);  
      Green = Random.nextint (255);  
  
      Blue = Random.nextint (255);  
      Draws the validation 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);  
    ///Save the four-digit CAPTCHA to the session.  
    HttpSession session = Req.getsession ();  
  
    Session.setattribute ("Validatecode", randomcode.tostring ());  
    Disables image caching.  
    Resp.setheader ("Pragma", "No-cache");  
    Resp.setheader ("Cache-control", "No-cache");  
  
    Resp.setdateheader ("Expires", 0);  
  
    Resp.setcontenttype ("Image/jpeg");  
    Outputs the image to the servlet output stream.  
    Servletoutputstream SOS = Resp.getoutputstream ();Imageio.write (buffimg, "JPEG", SOS);  
  Sos.close ();
}} import Java.awt.Color;
Import Java.awt.Font;
Import Java.awt.Graphics2D;
Import Java.awt.image.BufferedImage;

Import Java.util.Random;
Import Javax.imageio.ImageIO;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletOutputStream;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import javax.servlet.http.HttpSession;
 public class Verifycodeservlet extends HttpServlet {//Verify code picture width.

 private int width = 60;
 The height of the verification code picture.

 private int height = 20;

 Number of authentication code 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 ', ' O ', ' P ', ' Q ', ' R ', ' S ', '

 T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z ', ' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '}; /** * Initialize Verify picture properties/public void init () throWS Servletexception {//Web.xml get initial information//width String strwidth = this.getinitparameter ("width");
 Height String strheight = this.getinitparameter ("height");

 Number of characters String Strcodecount = This.getinitparameter ("Codecount");
  Converts the configured information to a numeric try {if (strwidth!= null && strwidth.length ()!= 0) {width = Integer.parseint (strwidth);
  } if (strheight!= null && strheight.length ()!= 0) {height = Integer.parseint (strheight);
  } if (Strcodecount!= null && strcodecount.length ()!= 0) {codecount = Integer.parseint (Strcodecount);
 The catch (NumberFormatException e) {} x = width/(codecount + 1);
 Fontheight = height-2;

 Codey = height-4; } protected void Service (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, Java.io.IOExceptio
 n {//define image buffer BufferedImage buffimg = new BufferedImage (width, height, bufferedimage.type_int_rgb);

 Graphics2D g = buffimg.creategraphics (); Create a random number generator class Random RandOm = new Random ();
 Fill 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 be based on the height of the picture.
 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 generated 160 lines of interference, so that the image of the authentication code is not easily detected by other programs.
 G.setcolor (Color.Black);
  for (int i = 0; i < 160 i++) {int x = random.nextint (width);
  int y = random.nextint (height);
  int xl = Random.nextint (12);
  int yl = Random.nextint (12);
 G.drawline (x, y, X + xl, y + yl);
 The//Randomcode is used to save the randomly generated verification code so that the user can authenticate after logging in.
 StringBuffer Randomcode = new StringBuffer ();

 int red = 0, green = 0, blue = 0;
 A validation code that randomly generates CODECOUNT numbers.
  for (int i = 0; i < Codecount i++) {//Get a randomly generated captcha number.
  String Strrand = string.valueof (Codesequence[random.nextint (36)]);
  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 = random.nextint (255);
  Green = Random.nextint (255);

  Blue = Random.nextint (255);
  Draws the validation 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);
 ///Save the four-digit CAPTCHA to the session.
 HttpSession session = Req.getsession ();

 Session.setattribute ("Validatecode", randomcode.tostring ());
 Disables image caching.
 Resp.setheader ("Pragma", "No-cache");
 Resp.setheader ("Cache-control", "No-cache");

 Resp.setdateheader ("Expires", 0);

 Resp.setcontenttype ("Image/jpeg");
 Outputs the image to the servlet output stream.
 Servletoutputstream SOS = Resp.getoutputstream ();
 Imageio.write (buffimg, "JPEG", SOS);
 Sos.close (); }

}

Resultservlet.java

Java code

Import java.io.IOException;  
  
Import Java.io.PrintWriter;  
Import javax.servlet.ServletException;  
Import Javax.servlet.http.HttpServlet;  
Import Javax.servlet.http.HttpServletRequest;  
  
Import Javax.servlet.http.HttpServletResponse;  
   The public class Resultservlet extends HttpServlet {/** * The Doget method of the servlet. <br> *  
   * This is called when a form has it tag value method equals to get. * @param request the request send by the ' client to the ' server * @param response the response send by the serve  
   R to the client * @throws servletexception If a error occurred * @throws IOException if an error occurred */public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexce  
  ption {doPost (request, response); /** * The DoPost method of the servlet. <br> * This is called when a form has its tag value methoD equals to post. * @param request the request send by the ' client to the ' server * @param response the response send by the serve  
   R to the client * @throws servletexception If a error occurred * @throws IOException if an error occurred */public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexc  
    eption {response.setcontenttype ("text/html;charset=utf-8");  
    String Validatec = (string) request.getsession (). getattribute ("Validatecode");  
    String Verycode = Request.getparameter ("C");  
    PrintWriter out = Response.getwriter (); if (verycode==null| | "".  
    Equals (Verycode)) {out.println ("Validation code is empty");  
      }else{if (validatec.equals (Verycode)) {out.println ("Verify code correct");  
      }else{out.println ("Validation code error");  
    } out.flush ();  
  Out.close ();
}} import java.io.IOException;

Import Java.io.PrintWriter; Import Javax.servlet.SeRvletexception;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;  public class Resultservlet extends HttpServlet {/** * The Doget method of the servlet. <br> *
 Called when a form has its tag value is equals to get. * @param request the request send by the "client to the" server * @param response the response send by the "server to TH" E Client * @throws servletexception If an error occurred * @throws IOException If a error occurred * * public void DoG ET (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException {doPost (request, RE
 Sponse); /** * The DoPost method of the servlet.
 <br> * * This are called when a form has it tag value method equals to post. * @param request the request send by the "client to the" server * @param response the response send by the "server to TH" E Client * @throws SERVLETEXCEPtion if an error occurred * @throws IOException If a error occurred/public void DoPost (HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {response.setcontenttype ("text/html;charset=
 Utf-8 ");
 String Validatec = (string) request.getsession (). getattribute ("Validatecode");
 String Verycode = Request.getparameter ("C");
 PrintWriter out = Response.getwriter (); if (verycode==null| | "".
 Equals (Verycode)) {out.println ("Validation code is empty");
  }else{if (validatec.equals (Verycode)) {out.println ("Verify code correct");
  }else{out.println ("Validation code error");
 } out.flush ();
 Out.close (); }

}

Verifycode.js

JS Code

function changeimg () {var imgsrc = $ ("#imgObj");  
  var src = imgsrc.attr ("src");  
Imgsrc.attr ("src", Chgurl (SRC));  
  }//timestamp//To make the picture inconsistent each time, the browser does not read the cache, so you need to add the timestamp function chgurl (URL) {var timestamp = (new Date ()). valueof ();  
  url = url.substring (0,17);  
  if ((Url.indexof ("&") >=0)) {url = url + "xtamp=" + timestamp;  
  }else{url = url + "? timestamp=" + timestamp;  
} return URL;  
  function Isrightcode () {var code = $ ("#veryCode"). attr ("value");  
  Code = "C=" + code;  
$.ajax ({type: "POST", url: "Resultservlet", Data:code, success:callback});  
function callback (data) {$ ("#info"). HTML (data);
 function changeimg () {var imgsrc = $ ("#imgObj");
 var src = imgsrc.attr ("src");
Imgsrc.attr ("src", Chgurl (SRC));
 }//timestamp//To make the picture inconsistent each time, the browser does not read the cache, so you need to add the timestamp function chgurl (URL) {var timestamp = (new Date ()). valueof ();
 url = url.substring (0,17); if ((Url.indexof ("&") >=0)) {url = url + "xtamp= "+ timestamp;
 }else{url = url + "? timestamp=" + timestamp;
} return URL;
 function Isrightcode () {var code = $ ("#veryCode"). attr ("value");
 Code = "C=" + code;
$.ajax ({type: "POST", url: "Resultservlet", Data:code, success:callback}); function callback (data) {$ ("#info"). HTML (data);

verifycode.jsp

HTML code

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

Above this jquery implementation of no refresh verification Code Simple example is small set to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud habitat community.

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.