Detailed explanation of how to parse Java to implement the Random verification code Function

Source: Internet
Author: User

The random code function added to many system registration, logon, or publishing information modules is to avoid the use of automatic registration or publishing programs.
The verification code is to randomly select some characters to display on the page in the form of images. If you submit a verification code, you must submit the characters on the image at the same time, if the submitted characters are different from those saved by the server session, the submitted information is considered invalid. In order to avoid automatic program analysis and resolution of images, it is usually possible to randomly generate some interference lines on the images or distort the characters to increase the difficulty.
We can use servlet to implement Random verification codes.
Copy codeThe Code is as follows: 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;
/**
* Generate a random Verification Code
* @ Author bitiliu
*
*/
Public class ValidateCodeServlet extends HttpServlet
{
Private static final long serialVersionUID = 1L;
// The image width of the verification code.
Private int width = 60;
// Height of the Verification Code image.
Private int height = 20;
// Number of characters in the verification code
Private int codeCount = 4;
Private int x = 0;
// Font height
Private int fontHeight;
Private int codeY;
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 and verify image attributes
*/
Public void init () throws ServletException
{
// Obtain the initial information from web. xml
// Width
String strWidth = this. getInitParameter ("width ");
// Height
String strHeight = this. getInitParameter ("height ");
// Number of characters
String strCodeCount = this. getInitParameter ("codeCount ");
// Convert the configuration information to a 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)
{}
X = width/(codeCount + 1 );
FontHeight = height-2;
CodeY = height-4;
}
Protected void service (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, java. io. IOException {
// Define the Image buffer
BufferedImage buffImg = new BufferedImage (
Width, height, BufferedImage. TYPE_INT_RGB );
Graphics2D g = buffImg. createGraphics ();
// Create a random number generator class
Random random = new Random ();
// Fill the image in white
G. setColor (Color. WHITE );
G. fillRect (0, 0, width, height );
// Create a font. The font size depends on the Image Height.
Font font = new Font ("Fixedsys", Font. PLAIN, fontHeight );
// Set the font.
G. setFont (font );
// Draw a border.
G. setColor (Color. BLACK );
G. drawRect (0, 0, width-1, height-1 );
// Generates 160 random interference lines, making it difficult for other programs to detect the authentication codes in the image.
G. setColor (Color. BLACK );
For (int I = 0; I <160; 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 ();
Int red = 0, green = 0, blue = 0;
// Generate a random codeCount verification code.
For (int I = 0; I <codeCount; I ++ ){
// Obtain the Random verification code number.
String strRand = String. valueOf (codeSequence [random. nextInt (36)]);
// Generate a random color component to construct the color value, so that the color values of each output number are different.
Red = random. nextInt (255 );
Green = random. nextInt (255 );
Blue = random. nextInt (255 );
// Use a random color to draw the verification code into the image.
G. setColor (new Color (red, green, blue ));
G. drawString (strRand, (I + 1) * x, codeY );
// Combine the four random numbers.
RandomCode. append (strRand );
}
// Save the four-digit verification code to the Session.
HttpSession session = req. getSession ();
Session. setAttribute ("validateCode", randomCode. toString ());
// Disable image caching.
Resp. setHeader ("Pragma", "no-cache ");
Resp. setHeader ("Cache-Control", "no-cache ");
Resp. setDateHeader ("Expires", 0 );
Resp. setContentType ("image/jpeg ");
// Output the image to the Servlet output stream.
ServletOutputStream sos = resp. getOutputStream ();
ImageIO. write (buffImg, "jpeg", sos );
Sos. close ();
}
}

Servlet needs to be declared in web. xml
Copy codeThe Code is as follows: <servlet>
<Servlet-name> ValidateCodeServlet </servlet-name>
<Servlet-class> com. servlet. ValidateCodeServlet </servlet-class>
<Init-param>
<Param-name> width </param-name>
<Param-value> 200 </param-value>
</Init-param>
<Init-param>
<Param-name> height </param-name>
<Param-value> 80 </param-value>
</Init-param>
<Init-param>
<Param-name> codeCount </param-name>
<Param-value> 5 </param-value>
</Init-param>
</Servlet>
<Servlet-mapping>
<Servlet-name> ValidateCodeServlet </servlet-name>
<Url-pattern>/validateCodeServlet </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.