Java Web Verification Code implementation code sharing _java

Source: Internet
Author: User
Tags rand java web

the role of verification code: usually login or registration system, users will be required to enter the verification code, to distinguish between user behavior and computer program behavior, the purpose is to prevent malicious registration, brute force to crack passwords.

implementation of the Code of thought: the server to achieve the random generation of digital and letter composition of the picture function, with JSP page to achieve display verification code and user input verification code function, and then use the server class to obtain pictures and user input data, judge two data is consistent.
Code Implementation

1. Write digital, English randomly generated server class, source code:

Package com;
Import Java.awt.Color;
Import Java.awt.Font;
Import Java.awt.Graphics;
Import Java.awt.image.BufferedImage;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;

Import Java.io.PrintWriter;
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 Logcheck extends HttpServlet {public Logcheck () {super (); 
 public void Destroy () {Super.destroy ();

  public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
 DoPost (request, response);  /* Implementation Core code */public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception,
  IOException {response.setcontenttype ("image/jpeg"); HttpSession Session=request.getsessiOn ();
  int width=60;
  
  int height=20;
  Set browser do not cache this picture Response.setheader ("Pragma", "No-cache");
  Response.setheader ("Cache-control", "No-cache");
  
  Response.setdateheader ("Expires", 0);
  Create the memory image and get the graphics context BufferedImage image=new bufferedimage (width, height,bufferedimage.type_int_rgb);
  
  Graphics G=image.getgraphics ();
  * * Generate a random Verification code * Definition Verification Code of the character chart/string chars= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  Char[] Rands=new char[4];
   for (int i=0;i<4;i++) {int rand= (int) (Math.random () *36);
  Rands[i]=chars.charat (RAND);
  * * * Generate image * Draw background/G.setcolor (new Color (0xDCDCDC));
  
  G.fillrect (0, 0, width, height);
   * * * Randomly generated 120 interference points */for (int i=0;i<120;i++) {int x= (int) (Math.random () *width);
   int y= (int) (Math.random () *height);
   int red= (int) (Math.random () *255);
   int green= (int) (Math.random () *255);
   int blue= (int) (Math.random () *255);
   G.setcolor (New Color (Red,green,blue));
  G.drawoval (x, y, 1, 0); } G.setcolor(Color.Black); G.setfont (new Font (NULL, font.italic|
  
  font.bold,18));
  The different characters of the output captcha at different heights g.drawstring ("" +rands[0], 1, 17);
  g.DrawString ("" "+rands[1], 16, 15);
  g.DrawString ("" "+rands[2], 31, 18);
  g.DrawString ("" "+rands[3], 46, 16);
  
  G.dispose ();
  Upload the image to the client Servletoutputstream Sos=response.getoutputstream ();
  Bytearrayoutputstream baos=new Bytearrayoutputstream ();
  Imageio.write (Image, "JPEG", BAOs);
  Byte[] Buffer=baos.tobytearray ();
  Response.setcontentlength (buffer.length);
  Sos.write (buffer);
  Baos.close ();
  
  Sos.close ();
 Session.setattribute ("Checkcode", New String (Rands));
 public void Init () throws Servletexception {//Put your code here}}

2. The page used to display the verification code :

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% String Path = Request.getcontextpath ()
;
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

3. To verify that the input is correct:

Package com;
Import java.io.IOException;

Import Java.io.PrintWriter;
Import javax.jms.Session;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import javax.servlet.http.HttpSession;
 public class Yanzheng extends HttpServlet {public Yanzheng () {super (); 
 public void Destroy () {Super.destroy ();

  public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
 DoPost (request, response); }/* Core code */public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioex
  ception {String info=null;

  /* Gets the value of the input/String value1=request.getparameter ("name");
  /* Get the value of the picture * * HttpSession session=request.getsession ();

  String value2= (String) session.getattribute ("Checkcode");
 /* Compare two values (letter case-insensitive)/if (Value2.equalsignorecase (value1)) {info= "Verify code input correct"; }else{info= "Authentication code input Error";
  } System.out.println (info);
  Request.setattribute ("info", info);
 Request.getrequestdispatcher ("/login.jsp"). Forward (request, response);
 public void Init () throws Servletexception {//Put your code here}}

4. Display input structure interface (input verification code is correct):  

 <%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <%
String path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  
 

5. Project structure, Effect screenshot:

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.