Java verification code generation program

Source: Internet
Author: User

 

The code is as follows: Copy code

Package com. logcd. 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 .*;
Import java. io .*;
Import javax. servlet. http .*;
Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
 
@ SuppressWarnings ("serial ")
Public class RandomCode extends HttpServlet {
 
Public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
 
This. doPost (request, response );
    }
 
Public void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
 
// The image width of the verification code.
Int width = 70;
// Height of the verification code image.
Int height = 30;
BufferedImage buffImg = new BufferedImage (width, height,
BufferedImage. TYPE_INT_RGB );
Graphics2D g = buffImg. createGraphics ();
 
// Create a random number generator class.
Random random = new Random ();
 
// Set the background color of the image (because it is a background, so it is light)
G. setColor (getRandColor (200,250 ));
G. fillRect (0, 0, width, height );
// Create a font. The font size depends on the image height.
Font font = new Font ("Times New Roman", Font. HANGING_BASELINE, 28 );
// Set the font.
G. setFont (font );
 
// Draw a border.
G. setColor (Color. BLACK );
G. drawRect (0, 0, width-1, height-1 );
// Generates 155 random interference lines, making it difficult for other programs to detect the authentication codes in the image.
// G. setColor (Color. GRAY );
G. setColor (getRandColor (160,200 ));
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 );
G. drawLine (x, y, x + xl, y + yl );
         }
 
// RandomCode is used to save the randomly generated verification code so that the user can perform verification after logon.
StringBuffer randomCode = new StringBuffer ();
 
// Four verification codes are generated by default.
Int length = 4;
// Set the alternative verification code, including "a-z" and number "0-9"
String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";

Int size = base. length ();
 
// A four-digit verification code is randomly generated.
For (int I = 0; I <length; I ++ ){
// Obtain the random verification code number.
Int start = random. nextInt (size );
String strRand = base. substring (start, start + 1 );
 
// Use a random color to draw the verification code into the image.
// Generate a random color (because it is a foreground, so it is too deep)
// G. setColor (getRandColor (1,100 ));
            
// The color of the called function is the same. It may be because the seed is too close and can only be directly generated.
G. setColor (new Color (20 + random. nextInt (110), 20 + random. nextInt (110), 20 + random. nextInt (110 )));
 
G. drawString (strRand, 15 * I + 6, 24 );
 
// Combine the four random numbers.
RandomCode. append (strRand );
         }
// Save the four-digit verification code to the Session.
HttpSession session = request. getSession ();
Session. setAttribute ("rand", randomCode. toString ());

// The image takes effect
G. dispose ();
 
// Disable image caching.
Response. setHeader ("Pragma", "no-cache ");
Response. setHeader ("Cache-Control", "no-cache ");
Response. setDateHeader ("Expires", 0 );
 
Response. setContentType ("image/jpeg ");
 
// Output the image to the Servlet output stream.
ServletOutputStream sos = response. getOutputStream ();
ImageIO. write (buffImg, "jpeg", sos );
Sos. flush ();
Sos. close ();

     }
 
Color getRandColor (int fc, int bc) {// Obtain a random Color from a given range
Random random = new Random ();
If (fc> 255)
Fc = 255;
If (bc> 255)
Bc = 255;
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 );
     }
 
 }

 

2. Configuration

The code is as follows: Copy code

<Servlet>
<Servlet-name> RandomCode </servlet-name>
<Servlet-class> com. logcd. servlet. RandomCode </servlet-class>
</Servlet>
<Servlet-mapping>
<Servlet-name> RandomCode </servlet-name>
<Url-pattern>/randomCode </url-pattern>
</Servlet-mapping>

3. Call

The code is as follows: Copy code

<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312"/>
<Meta http-equiv = "pragma" content = "no-cache"/>
<Meta http-equiv = "cache-control" content = "no-cache"/>
<Meta http-equiv = "expires" content = "0"/>

<Iframe src = "http: // 127.0.0.1/js_test/randomCode" id = "codeFrame" name = "codeFrame" frameborder = "no" border = "0" marginwidth = "0"
Marginheight = "0" scrolling = "no" allowtransparency = "yes" height = "35" width = "102"> </iframe>
<A href = "javascript: void (0);" onclick = "refreshCode ();"> can't see clearly, change one </a>
<Br>
<Span id = "codeImg"> </span>
<A href = "javascript: void (0);" onclick = "reloadCode ()"> I can't see it clearly. I need another one. </a>

Function $ (id ){
Return document. getElementById (id );
 }
 
/** Refresh iframe **/
Function refreshCode (){
Window. frames ["codeFrame"]. location. reload ();
 }
 
/** Replace image **/
Function reloadCode (){
$ ("CodeImg"). innerHTML = " ";
 }

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.