An example of a Java color Verification Code

Source: Internet
Author: User

Image Generation and verification class verifycodegenerator. Java is from http://www.blogjava.net/wuxingjia/archive/2008/04/05/410893.htmlhere!

The demo is as follows:

1. webproject:

2. source file:

1. verifycodegenerator. Java (Source: http://www.blogjava.net/wuxingjia/archive/2008/04/05/190893.html)

Import java. AWT. color;
Import java. AWT. Font;
Import java. AWT. graphics;
Import java. AWT. image. bufferedimage;
Import java. Io. ioexception;
Import java. util. Random;
Import javax. servlet. servletoutputstream;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;
Import com.sun.image.codec.jpeg. Unzip codec;
Import com.sun.image.codec.jpeg. encode imageencoder;
/**
* @ (#) Verifycodeservlet. Java Dec 9, 2007 8:14:14
*
* @ Author yuan
* Verification code generator. To use this class, set the name attribute of the verification code input box in the form to "verifycode"
*/
Public class verifycodegenerator {

Private Static final verifycodegenerator generator = new verifycodegenerator ();

Private final string attribute_name = "verifycode ";
// The Image Width
Private Final int width = 15;
// Image Height
Private Final int Height = 22;
// String Length
Private Final int code_length = 4;
// Random string range
Private final string rand_range = "abcdefghijklmnopqrstuvwxyz"
+ "Abcdefghijklmnopqrstuvwxyz"
+ "1234567890"
+ "@ # Quot ";

Private Final char [] chars = rand_range.tochararray ();

Private random = new random ();

Private verifycodegenerator (){
//
}

Public static verifycodegenerator getinstance (){
Return generator;
}

/**
* Generate random strings
* @ Return random string
*/
Private string getrandstring (){
Stringbuilder sb = new stringbuilder ();
For (INT I = 0; I <code_length; I ++)
SB. append (chars [random. nextint (chars. Length)]);
Return sb. tostring ();
}

/**
* Generate random colors
* @ Param ll lower limit of color value (lower limit)
* @ Param ul the upper limit of the color value (upper limit)
* @ Return: Random color object generated
*/
Private color getrandcolor (int ll, int UL ){
If (LL> 255) LL = 255;
If (LL <1) LL = 1;
If (UL> 255) UL = 255;
If (UL <1) UL = 1;
If (UL = ll) UL = LL + 1;
Int r = random. nextint (ul-LL) + ll;
Int G = random. nextint (ul-LL) + ll;
Int B = random. nextint (ul-LL) + ll;
Color color = new color (R, G, B );
Return color;
}

/**
* Generate image data of the specified string
* @ Param verifycode: the random string to be printed
* @ Return: image data generated
**/
Private bufferedimage getimage (string verifycode ){

Bufferedimage image = new bufferedimage (width * code_length, height, bufferedimage. type_int_rgb );

// Obtain the image Context
Graphics graphics = image. getgraphics ();

// Set the background color
Graphics. setcolor (getrandcolor (1, 50 ));
// Fill in the background color
Graphics. fillrect (0, 0, width * 4, height );

// Set the border color
Graphics. setcolor (new color (0,255, 0 ));
// Draw a border
For (INT I = 0; I <2; I ++)
Graphics. drawrect (I, I, width * code_length-I * 2-1, height-I * 2-1 );

// Set the random interference line color
Graphics. setcolor (getrandcolor (50,100 ));
// Generate 50 interference lines
For (INT I = 0; I <50; I ++ ){
Int X1 = random. nextint (width * code_length-4) + 2;
Int Y1 = random. nextint (height-4) + 2;
Int X2 = random. nextint (width * code_length-2-X1) + x1;
Int y2 = Y1;
Graphics. drawline (x1, Y1, X2, Y2 );
}

// Set the font
Graphics. setfont (new font ("Times New Roman", Font. Plain, 18 ));
// Draw a string
For (INT I = 0; I <this. code_length; I ++ ){
String temp = verifycode. substring (I, I + 1 );
Graphics. setcolor (getrandcolor (100,255 ));
Graphics. drawstring (temp, 13 * I + 6, 16 );
}

// The image takes effect
Graphics. Dispose ();

Return image;
}

/**
* Output the image of the Verification Code
* @ Param request the user's request object
* @ Param response the response object of the user
**/
Public void printimage (httpservletrequest request,
Httpservletresponse response ){
// Set contenttype to "image/JPEG" for the browser to recognize the image format.
Response. setcontenttype ("image/JPEG ");
// Set the page not to cache
Response. setheader ("Pragma", "No-Cache ");
Response. setheader ("cache-control", "No-Cache ");
Response. setdateheader ("expires", 2000 );

// Obtain the Random verification code
String verifycode = This. getrandstring ();
String STR = "ssss ";
For (INT I = 0; I <10; I ++)
STR = STR + STR;
// Obtain the image data of the Verification Code
Bufferedimage Bi = This. getimage (verifycode );
// Save the verification code to the session
Request. getsession (). setattribute (attribute_name, verifycode );
Try {
// Obtain the servlet output stream
Servletoutputstream outstream = response. getoutputstream ();
// Create an encoder that can encode image data as JPEG data streams
Required imageencoder encoder = required codec. createjpegencoder (outstream );
// Encode the image data
Encoder. encode (BI );
// Forcibly input the buffer content to the page
Outstream. Flush ();
// Close the output stream
Outstream. Close ();
} Catch (ioexception ex ){
Ex. printstacktrace ();
}
}

/**
* Check whether the entered verification code is correct. If the entered verification code matches the generated verification code, true is returned. Otherwise, false is returned.
* @ Param request the user's request object
* @ Return verification result
**/
Public Boolean check (httpservletrequest request ){
If (string) request. getparameter (attribute_name ))
. Inclusignorecase (string) request. getsession (). getattribute (attribute_name ))){
Request. getsession (). removeattribute (attribute_name );
Return true;
}
Return false;
}
}

2. image. Java (this servlet calls the output image)

Import java. Io. ioexception;

Import javax. servlet. servletexception;
Import javax. servlet. http. httpservlet;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;

Public class image extends httpservlet
{

@ Override
Protected void Service (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception
{
Verifycodegenerator VG = verifycodegenerator. getinstance ();

VG. printimage (request, response );
}
}

3. login (this servlet processes form input)

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 login extends httpservlet
{
 
Public void doget (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception
{
Dopost (request, response );
}

Public void dopost (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception
{
Verifycodegenerator VG = verifycodegenerator. getinstance ();

String vcode = request. getparameter ("verifycode ");
If (null = vcode | "" = vcode. Trim ())
{
Request. setattribute ("error", "Enter the verification code! ");
Request. getrequestdispatcher ("index. jsp"). Forward (request, response );
}
Else if (true = VG. Check (request ))
Request. getrequestdispatcher ("success. jsp"). Forward (request, response );
Else
{

Request. setattribute ("error", "Incorrect verification code. Please enter it again! ");
Request. getrequestdispatcher ("index. jsp"). Forward (request, response );
}

}
}

4. Web. xml

<? XML version = "1.0" encoding = "UTF-8"?>
<Web-app version = "2.4"
Xmlns = "http://java.sun.com/xml/ns/j2ee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemalocation = "http://java.sun.com/xml/ns/j2ee
Http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>

<Servlet>
<Servlet-Name> login </servlet-Name>
<Servlet-class> login </servlet-class>
</Servlet>
<Servlet>
<Servlet-Name> image </servlet-Name>
<Servlet-class> image </servlet-class>
</Servlet>

<Servlet-mapping>
<Servlet-Name> login </servlet-Name>
<URL-pattern>/login </url-pattern>
</Servlet-mapping>

<Servlet-mapping>
<Servlet-Name> image </servlet-Name>
<URL-pattern>/image </url-pattern>
</Servlet-mapping>


<Welcome-file-List>
<Welcome-File> index. jsp </welcome-File>
</Welcome-file-List>
</Web-app>

5. index. jsp

<% @ Page Language = "Java" Import = "Java. util. *" pageencoding = "UTF-8" %>

<HTML>
<Head>
<SCRIPT type = "text/JavaScript">
Function refresh ()
{
Document. getelementbyid ("image"). src = 'image? Now = '+ new date ();
}
</SCRIPT>

<Title> index </title>
</Head>
<Body>
<Form action = "login">
<Table>
<Tr>
<TD> Verification Code: <input type = "text" name = "verifycode" size = "4"> <a href = "#" onclick = ""Refresh () "> <input type =" button "value =" refresh "/> </a> </TD>
</Tr>
<% IF (null! = Request. getattribute ("error") {%> <tr> <TD> <% = request. getattribute ("error") %> </TD> </tr> <%} %>
</Table>
<Input type = "Submit" value = "Submit">
</Form>
</Body>
</Html>

6. Successful success return page

<% @ Page Language = "Java" Import = "Java. util. *" pageencoding = "UTF-8" %>

<HTML>
<Head>
<Title> sucess </title>
</Head>
<Body>
Success!
</Body>
</Html>

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.