Java generates a Random verification code, supporting uppercase and lowercase letters and numbers; random font

Source: Internet
Author: User

Java generates a Random verification code, which can generate numbers, uppercase letters, and lowercase letters at random. You can also randomly generate text fonts and sizes. The font size may vary depending on the image.

Package com. Hoo. util;

Import java. AWT. color;
Import java. AWT. Font;
Import java. AWT. graphics;
Import java. AWT. image. bufferedimage;
Import java. util. Random;

Import javax. ImageIO. ImageIO;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;
/**
* <B> function: </B> Verification Code Generation Tool
* @ Project NetworkService
* @ Package com. Hoo. util
* @ Filename validcodeutils. Java
* @ Createdate 03:05:50 pm
* @ Author hoojo
*/
@ Suppresswarnings ("UNUSED ")
Public class validcodeutils {
/*************************************** ******************************
* Verification Code width
*/
Public static int width = 60;
/***
* Verification Code height
*/
Public static int Height = 20;
 
/*************************************** *******************************
* The Verification Code background color color_fc_bg should be smaller than color_bc_bg
*/
Public static int color_fc_bg = 200;
/***
* The Verification Code background color color_fc_bg should be smaller than color_bc_bg
*/
Public static int color_bc_bg = 250;
 
/*************************************** *******************************
* The Color of the Verification Code background interference line color_fc_line should be smaller than color_bc_line
*/
Public static int color_fc_line = 160;
/***
* The Color of the Verification Code background interference line color_fc_line should be smaller than color_bc_line
*/
Public static int color_bc_line = 200;
 
/*************************************** ************************************
* The verification code color color_fc_code should be smaller than color_bc_code
*/
Public static int color_fc_code = 20;
/***
* The verification code color color_fc_code should be smaller than color_bc_code
*/
Public static int color_bc_code = 170;
 
/*************************************** ************************************
* Generate colors in the specified range
* @ Param FC: The FC color value is less than 255.
* @ Param BC the BC color value is less than 255
* @ Return color
*/
Private Static color getrandcolor (int fc, int BC ){
Random random = new random ();
If (FC <0)
Fc = 0;
If (Bc <0)
BC = 1;
If (FC> 255)
Fc = 255;
If (BC> 255)
BC = 255;
If (BC = FC)
BC + = 10;
Int temp = 0;
If (Bc <FC ){
Temp = BC;
BC = FC;
Fc = temp;
}
Int r = FC + random. nextint (BC-Fc );
Int G = FC + random. nextint (BC-Fc );
Int B = FC + random. nextint (BC-Fc );
Return new color (R, G, B );
}

/**
* <B> function: </B> Image Generation Method
* @ Createdate 03:06:22 pm
* @ Author hoojo
* @ Param request httpservletrequest
* @ Param response httpservletresponse
* @ Return Boolean
* @ Throws exception
*/
Public static Boolean getimage (httpservletrequest request, httpservletresponse response) throws exception {
Response. Reset ();
Response. setcontenttype ("image/JPEG ");
// Set the page not to cache
Response. setheader ("Pragma", "No-Cache ");
Response. setheader ("cache-control", "No-Cache ");
Response. setdateheader ("expires", 0 );
// Create an image in memory
Bufferedimage image = new bufferedimage (width, height, bufferedimage. type_int_rgb );

// Obtain the image Context
Graphics IMG = image. getgraphics ();
// Generate a random class
Random random = new random ();

// Set the background color
IMG. setcolor (getrandcolor (color_fc_bg, color_bc_bg ));
IMG. fillrect (0, 0, width, height );

// Set the font
IMG. setfont (new font ("Times New Roman", Font. Plain, 18 ));

// Draw a border
// G. setcolor (new color ());
// G. drawrect (0, 0, width-1, height-1 );

// Generates 155 random interference lines, making the authentication code in the image hard to be detected by other programs.
IMG. setcolor (getrandcolor (color_fc_line, color_bc_line ));
For (INT I = 0; I <155; I ++ ){
Int x = random. nextint (width );
Int y = random. nextint (height );
Int XL = random. nextint (12 );
Int yl = random. nextint (12 );
IMG. drawline (X, Y, x + XL, Y + yl );
}

// Obtain the random ID code (4 digits)
String codevalue = "";
For (INT I = 0; I <4; I ++ ){
// String Rand = string. valueof (random. nextint (10 ));
String Rand = getrandomchar ();
Codevalue = codevalue. Concat (RAND );
IMG. setfont (getrandomfont (); // random font
// Display the authentication code to the image
IMG. setcolor (getrandcolor (color_fc_code, color_bc_code ));
IMG. drawstring (RAND, 13 * I + 6, 16 );
}
Request. getsession (). setattribute ("codevalue", codevalue );
// The image takes effect
IMG. Dispose ();
// Output the image to the page
Return ImageIO. Write (image, "Jpeg", response. getoutputstream ());
}
 
/**
* Randomly generated characters, including uppercase letters, lowercase letters, and numbers
* <B> function: </B> Function
* @ Createdate 2010-8-23 10:33:55 AM
* @ Author hoojo
* @ Return
*/
Public static string getrandomchar (){
Int Index = (INT) math. Round (math. Random () * 2 );
String randchar = "";
Switch (INDEX ){
Case 0: // uppercase characters
Randchar = string. valueof (char) math. Round (math. Random () * 25 + 65 ));
Break;
Case 1: // lowercase characters
Randchar = string. valueof (char) math. Round (math. Random () * 25 + 97 ));
Break;
Default: // number
Randchar = string. valueof (math. Round (math. Random () * 9 ));
Break;
}
Return randchar;
}
 
/**
* <B> function: </B> the font and text size are randomly generated.
* @ Createdate 2010-8-23 10:44:22 AM
* @ Author hoojo
* @ Return
*/
Public static font getrandomfont (){
String [] fonts = {"Georgia", "verdana", "Arial", "tahoma", "Time News Roman", "Courier New", "Arial black ", "quantzite "};
Int fontindex = (INT) math. Round (math. Random () * (fonts. Length-1 ));
Int fontsize = (INT) math. Round (math. Random () * 4 + 16 );
Return new font (fonts [fontindex], Font. Plain, fontsize );
}
}

The verification code value is saved in the session: request. getsession (). setattribute ("codevalue", codevalue );
Check whether the value entered by the user is equal to the codevalue in the session;

The following is a JSP page call servlet: validcodeservlet. Java

Validcodeservlet calls the above validcodeutils Verification Code Generation Tool class

Package com. Hoo. servlet;

Import java. Io. ioexception;
Import javax. servlet. servletexception;
Import javax. servlet. http. httpservlet;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;

Import com. Hoo. util. validcodeutils;

@ Suppresswarnings ("serial ")
Public class validcodeservlet extends httpservlet {
 
Public void doget (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {
Try {
Validcodeutils. getimage (request, response );
} Catch (exception e ){
E. printstacktrace ();
}
}

Public void dopost (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {
Doget (request, response );
}
}

 

Call the servlet method on the JSP page.

 

JS: reloadvalidcode Method

Function reloadvalidcode (o ){
O. src = "$ {pagecontext. Request. contextpath}/validcodeservlet? Timed = "+ new date (). getmilliseconds ();
}
Here, "timed =" + new date (). getmilliseconds (); is used to prevent ie cache.

HTML Tag:

You can directly configure the URL with the servlet name, which corresponds to the Web. xml configuration. The main call path $ {pagecontext. Request. contextpath}/validcodeservlet will carry the root directory, which is relatively safe.

Validcodeservlet configuration in Web. xml
<Servlet>
<Servlet-Name> validcodeservlet </servlet-Name>
<Servlet-class> com. Hoo. servlet. validcodeservlet </servlet-class>
</Servlet>

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

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.