Java generates a Random verification code (supporting uppercase/lowercase letters, numbers, and random fonts ).

Source: Internet
Author: User

The Code is as follows:

Copy codeThe Code is as follows: 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>

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.