Example of the generation of Java EE Verification Code

Source: Internet
Author: User
Tags numeric value browser cache stringbuffer

First, the preface
The advantage of using a captcha in a form page is to effectively prevent users from submitting the form maliciously, or to use a plug-in to attack the system illegally.

Ii. Conditions of preparation
1, a common Web project webproject;
2, a Web server Tomcat.

Third, the production of verification Code actual combat

Realize the idea:
<1> Customize a servlet verifycodeservlet to draw a verification code picture that contains the validation characters, where the pictures need to be painted manually using Graphics2D;
<2> Use the img-labeled SRC reference to the servlet to display the servlet on a specific page;
<3> because of the drawing of the Verification Code information into the session, so submit the form can be based on the value saved in session and user input code to compare, verify that the input is correct.
The specific code is as follows:

The code is as follows Copy Code

Package com.servlet;

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;

/**
* The servlet that produces the verification code picture
* @author Administrator
*
*/
public class Verifycodeservlet extends HttpServlet {

Private static final long serialversionuid = -5051097528828603895l;

/**
* Verify the width of the code picture.
*/
private int width = 100;

/**
* Verify the height of the code picture.
*/
private int height = 30;

/**
* Number of verification code characters
*/
private int codecount = 4;

/**
* Font Height
*/
private int fontheight;

/**
* The x-axis value of the first character, because the following character coordinates are incremented sequentially, so their x-axis values are multiples of the Codex
*/
private int CodeX;

/**
* Codey, verifying the y-axis value of the character, because it is the same value
*/
private int Codey;

/**
* Codesequence indicates the sequence values that the character allows to appear
*/
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 the initial information from the Web.xml
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 value
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);
}
catch (NumberFormatException e) {
E.printstacktrace ();
}
Width-4 remove the left and right positions, so that the verification code more centralized display, reduce the more concentrated.
codecount+1//equal to the width of the distribution display, including the left and right sides of the space
CodeX = (width-4)/(codecount+1);
HEIGHT-10 Display Verification Code
Fontheight = height-10;
Codey = height-7;
}

/**
* @param request
* @param response
* @throws servletexception
* @throws java.io.IOException
*/
protected void Service (HttpServletRequest request, httpservletresponse response) throws Servletexception, java.io.IOException {
Define Image Buffer
BufferedImage buffimg = new BufferedImage (width, height, bufferedimage.type_int_rgb);
Graphics2D gd = Buffimg.creategraphics ();
Create a random number generator class
Random Random = new Random ();
To fill an image with white
Gd.setcolor (Color.light_gray);
Gd.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.
Gd.setfont (font);
Draw a border.
Gd.setcolor (Color.Black);
Gd.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.
Gd.setcolor (Color.gray);
for (int i = 0; i < i++) {
int x = random.nextint (width);
int y = random.nextint (height);
int xl = Random.nextint (12);
int yl = Random.nextint (12);
Gd.drawline (x, y, X + xl, y + yl);
}
Randomcode is used to save randomly generated CAPTCHA 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++) {
The number of validated codes generated randomly.
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.
Gd.setcolor (New Color (Red,green,blue));
Gd.drawstring (Strrand, (i + 1) * CodeX, Codey);
The resulting four random numbers are grouped together.
Randomcode.append (Strrand);
}
Saves a four-bit number of Authenticode to the session.
HttpSession session = Request.getsession ();
Session.setattribute ("Validatecode", randomcode.tostring ());
Disables image caching.
Response.setheader ("Pragma", "No-cache");
Response.setheader ("Cache-control", "No-cache");
Response.setdateheader ("Expires", 0);

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


The servlet that generates the CAPTCHA is then configured in Web.xml, as follows:

The code is as follows Copy Code


<servlet>
<servlet-name>VerifyCodeServlet</servlet-name>
<servlet-class>com.servlet.VerifyCodeServlet</servlet-class>
<init-param>
<param-name>width</param-name>
<param-value>120</param-value>
</init-param>
<init-param>
<param-name>height</param-name>
<param-value>32</param-value>
</init-param>
<init-param>
<param-name>codeCount</param-name>
<param-value>4</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>VerifyCodeServlet</servlet-name>
<url-pattern>/VerifyCodeServlet</url-pattern>
</servlet-mapping>


Start the server, enter in the browser address bar: Http://localhost:8080/webProject/VerifyCodeServlet


<1> Each refresh verification code varies, because the servlet has set the browser cache disabled.
<2> Here's a problem: if you use Firefox, the Serviice method overridden in Verifycodeservlet is executed two times, either as a rewrite Doget method or as a Dopost method, and the other browsers don't. It was later found that if the servlet was referenced through the page, it would call normal.

You can then reference the CAPTCHA in the page, 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" >
<meta http-equiv= "Content-type" content= "text/html; Charset=iso-8859-1 ">
<title>insert title here</title>
<body>
<div>
<%
String Inputcode = Request.getparameter ("Inputcode");
String verifycode = (string) session.getattribute ("Validatecode");
if (inputcode!=null && verifycode!=null) {
Out.print ("Real Verification Code:" + Verifycode + "<br/>" + "user input verification Code:" + Inputcode + "<br/>");
Inputcode = Inputcode.touppercase ();//case-insensitive
Out.print ("Comparison authentication code certificate user input" + (Inputcode.equals (verifycode)?) Correct ":" Error "+"! ");
}
%>
<form action= "index.jsp" >
Verification code: <input name= "Inputcode" value= ""/>
<br/>
<input name= "Submit" type= "Submission" value= "submitted"/>
</form>
</div>
<script>
function Refresh (obj) {
OBJ.SRC = "Verifycodeservlet" + math.random ();
}

function MouseOver (obj) {
Obj.style.cursor = "pointer";
}
</script>
</body>

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.