1. Ideas:
The verification code image on the page is servlet, and jquery is used for asynchronous verification of information.
2. Files used
Verifycodeservlet. Java -- Servlet used to generate images
Resultservlet. Java -- used to verify the correctness of the Verification Code
Servlet
Verifycode. js-verify the JS File
Jquery. JS -- source file in the jquery package
Verifycode. jsp -- page
3. Code
Verifycodeservlet. Java
Java code
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;
Public class verifycodeservlet extends httpservlet {
// 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 the authentication code in the image hard to be
It is detected by the program.
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 log on
Record for verification.
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 random color components to construct the color value.
The color values of each 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 ();
}
}
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;
Public class verifycodeservlet extends httpservlet {
// 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 the authentication code in the image hard to be explored by other programs
Measured.
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
Verify.
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 random color components to construct the color value, so that the color of each number is output.
The color values 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 ();
}
}
Resultservlet. Java
Java code
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 resultservlet extends httpservlet {
/**
* The doget method of the servlet. <br>
*
* This method is called when a form has its tag
Value Method equals to get.
*
* @ Param request the request send by the client
The server
* @ Param response the response send by the server
To the client
* @ Throws servletexception if an error occurred
* @ Throws ioexception if an error occurred
*/
Public void doget (httpservletrequest request,
Httpservletresponse response)
Throws servletexception, ioexception {
Dopost (request, response );
}
/**
* The dopost method of the servlet. <br>
*
* This method is called when a form has its tag
Value Method equals to post.
*
* @ Param request the request send by the client
The server
* @ Param response the response send by the server
To the client
* @ Throws servletexception if an error occurred
* @ Throws ioexception if an error occurred
*/
Public void dopost (httpservletrequest request,
Httpservletresponse response)
Throws servletexception, ioexception {
Response. setcontenttype
("Text/html; charsets = UTF-8 ");
String validatec = (string) request. getsession
(). Getattribute ("validatecode ");
String verycode = request. getparameter ("C ");
Printwriter out = response. getwriter ();
If (verycode = NULL | "". Equals (verycode )){
Out. println ("the verification code is blank ");
} Else {
If (validatec. Equals (verycode )){
Out. println ("correct Verification Code ");
} Else {
Out. println ("Incorrect verification code ");
}
}
Out. Flush ();
Out. Close ();
}
}
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 resultservlet extends httpservlet {
/**
* The doget method of the servlet. <br>
*
* This method is called when a form has its tag Value
Method equals to get.
*
* @ Param request the request send by the client to
Server
* @ Param response the response send by the server
The client
* @ Throws servletexception if an error occurred
* @ Throws ioexception if an error occurred
*/
Public void doget (httpservletrequest request,
Httpservletresponse response)
Throws servletexception, ioexception {
Dopost (request, response );
}
/**
* The dopost method of the servlet. <br>
*
* This method is called when a form has its tag Value
Method equals to post.
*
* @ Param request the request send by the client to
Server
* @ Param response the response send by the server
The client
* @ Throws servletexception if an error occurred
* @ Throws ioexception if an error occurred
*/
Public void dopost (httpservletrequest request,
Httpservletresponse response)
Throws servletexception, ioexception {
Response. setcontenttype ("text/html; charset = UTF-8 ");
String validatec = (string) request. getsession
(). Getattribute ("validatecode ");
String verycode = request. getparameter ("C ");
Printwriter out = response. getwriter ();
If (verycode = NULL | "". Equals (verycode )){
Out. println ("the verification code is blank ");
} Else {
If (validatec. Equals (verycode )){
Out. println ("correct Verification Code ");
} Else {
Out. println ("Incorrect verification code ");
}
}
Out. Flush ();
Out. Close ();
}
}
Verifycode. js
JS Code
Function changeimg (){
VaR imgsrc = $ ("# imgobj ");
VaR src = imgsrc. ATTR ("src ");
Imgsrc. ATTR ("src", chgurl (SRC ));
}
// Timestamp
// Add
Previous Timestamp
Function chgurl (URL ){
VaR timestamp = (new date (). valueof ();
Url = URL. substring (0, 17 );
If (URL. indexof ("&")> = 0 )){
Url = URL + "× tamp =" + timestamp;
} Else {
Url = URL + "? Timestamp = "+ timestamp;
}
Return URL;
}
Function isrightcode (){
VaR code = $ ("# verycode"). ATTR ("value ");
Code = "C =" + code;
$. Ajax ({
Type: "Post ",
URL: "resultservlet ",
Data: code,
Success: callback
});
}
Function callback (data ){
$ ("# Info" pai.html (data );
}
Function changeimg (){
VaR imgsrc = $ ("# imgobj ");
VaR src = imgsrc. ATTR ("src ");
Imgsrc. ATTR ("src", chgurl (SRC ));
}
// Timestamp
// Add
Previous Timestamp
Function chgurl (URL ){
VaR timestamp = (new date (). valueof ();
Url = URL. substring (0, 17 );
If (URL. indexof ("&")> = 0 )){
Url = URL + "× tamp =" + timestamp;
} Else {
Url = URL + "? Timestamp = "+ timestamp;
}
Return URL;
}
Function isrightcode (){
VaR code = $ ("# verycode"). ATTR ("value ");
Code = "C =" + code;
$. Ajax ({
Type: "Post ",
URL: "resultservlet ",
Data: code,
Success: callback
});
}
Function callback (data ){
$ ("# Info" pai.html (data );
}
Verifycode. jsp
HTML code
<% @ Page Language = "Java" contenttype = "text/html;
Charset = UTF-8"
Pageencoding = "UTF-8" %>
<! Doctype HTML public "-// W3C // dtd html 4.01
Transitional // en"
Http://www.w3.org/TR/html4/loose.dtd>
<HTML>
<Head>
<Meta http-equiv = "Content-Type"
Content = "text/html; charsets = UTF-8">
<SCRIPT type = "text/JavaScript"
Src = "JS/verifycode. js"> </SCRIPT>
<SCRIPT type = "text/JavaScript"
Src = "JS/jquery. js"> </SCRIPT>
<Title> test verify Code </title>
</Head>
<Body>
<Input id = "verycode" name = "verycode"
Type = "text"/>
Src = "verifycodeservlet"/>
<A href = "#" onclick = "changeimg ()"> change one </a>
<Input type = "button" value = "verify"
Onclick = "isrightcode ()"/>
<Div id = "info"> </div>
</Body>
</Html>