I. Main functions:
1. Supports pure numbers, uppercase letters, lowercase letters, and two-to-two or three mixed verification codes;
2. Supports the exclusion of custom special characters (for example, 0ooi1ji );
3. Two types of verification codes, image and text, are supported;
4. Supports custom Verification Code image size;
5. Support for custom interference lines;
6. Supports custom and random definition of image, text, and interference line colors;
Others: The <IFRAME> and Verification codes are displayed on the sample page.
A. Only Arabic numerals
Ii. Main Code
1. index. jsp
<% @ Page Language = "Java" Import = "Java. util. *" pageencoding = "UTF-8" %>
<%
String Path = request. getcontextpath ();
String basepath = request. getscheme () + ": //" + request. getservername () + ":" + request. getserverport () + path + "/";
%>
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en">
<HTML>
<Head>
<Title> <% = basepath %> </title>
</Head>
<SCRIPT type = "text/JavaScript">
VaR req;
// Submit a message
Function pubmsg (){
Msgtitle = Document. msgform. msgtitle. value;
Msgcontent = Document. msgform. msgcontent. value;
Verifycode = Document. msgform. verifycode. value;
// Check the input content format
If (msgtitle. Length <5 | msgcontent. Length <5 ){
Alert ("the title and content cannot be less than five characters ");
Return;
}
If (verifyCode. length = 0 ){
Alert ("Enter the Verification Code ");
Return;
}
// Obtain the XMLHttpRequest object
If (window. XMLHttpRequest)
Req = new XMLHttpRequest ();
Else if (window. ActiveXObject)
Req = new ActiveXObject ("Microsoft. XMLHTTP ");
// Submit the request
If (req ){
Req. onreadystatechange = callBack; // specify the server response result processing function (note that only the function name has no parentheses)
Url = "<% = path %>/servlet/PubMsgServlet? MsgTitle = "+ msgTitle +" & msgContent = "+ msgContent +" & verifyCode = "+ verifyCode;
Req. open ("GET", url, false );
Req. send ();
}
}
// Server response result processing function
Function callBack (){
If (req. readyState = 4 ){
If (req. status = 200 ){
Next = req. responseText; // obtain the server processing result
If (next = "this "){
Alert ("Incorrect verification code, please enter it again ");
VerifyCodeFrame. location. reload (); // refresh the verification code
} Else {
Document. msgForm. msgTitle. value = "";
Document. msgForm. msgContent. value = "";
Window. location = next; // jump to the page
}
} Else {
Alert (req. status + ":" + req. statusText );
}
}
Document. msgForm. verifyCode. value = "";
}
// Change the verification code
Function changeVerifyCode (){
// 1. If <IFRAME> is used, the content of <IFRAME> is reloaded.
// Verifycodeframe. Location. Reload ();
// 2. If is used, modify the URL of .
// Here is a tip: If the URL is assigned with the same value, the browser will not send a request again, so JavaScript will generate an instant parameter in the URL in milliseconds.
T = new date (). gettime ();
Document. msgform. verifycodeimg. src = "<% = PATH %>/servlet/verifycodeservlet? T = "+ T;
}
</SCRIPT>
<Body>
<Form name = "msgform" Action = "" method = "Post">
<Table border = 0>
<Tr>
<Td> title: </td>
<Td> <input name = "msgTitle" size = "65"/> </td>
</Tr>
<Tr>
<Td> content: </td>
<Td> <textarea name = "msgContent" rows = "10" cols = "64"> </textarea> </td>
</Tr>
<Tr>
<Td> Verification Code: </td>
<Td>
<Input name = "verifyCode" style = "height: 29px; width = 70px; font-size: 25px"/>
<! -- Below: TWO Verification Code display methods -->
<! -- 1. Use <iframe> to implement -->
<! --
<Iframe name = "verifyCodeFrame" src = "<% = path +"/servlet/VerifyCodeServlet "%>"
Width = "100" height = "30" frameborder = 0 align = "top" marginheight = 0 marginwidth = 0 scrolling = no> </iframe>
-->
<! -- 2. Use to implement -->
/servlet/verifycodeservlet" style = "cursor: Hand" align = "align" onclick = "changeverifycode () "/>
<! -- Above: TWO Verification Code display methods -->
<Font style = "color: Blue;"> <a href = "javascript: changeverifycode ()"> can't see it clearly? </A> </font> & nbsp;
<Input type = "button" value = "Publish a message" onclick = "pubmsg ()"/>
</TD>
</Tr>
</Table>
</Form>
</Body>
</Html>
2.org. javachina. util. verifycode. Java
Package org. javachina. util;
Import java. util. Random;
Import java. AWT. image. bufferedimage;
Import java. AWT. graphics;
Import java. AWT. Font;
Import java. AWT. color;
/**
* Verification code generator class, which can generate a combination of numbers, uppercase letters, and lowercase letters. Supports the number of characters in the Custom verification code, the size of the image of the custom verification code, and the special characters to be excluded;
* Supports the number of custom interference lines and the graphic color of the custom verification code.
*
* @ Author org. javachina
* @ Version 1.01
*/
Public class verifycode {
/**
* The verification code type is 0 to 0 ~ 9
*/
Public static final int type_num_only = 0;
/**
* The verification code is a combination of uppercase and lowercase letters.
*/
Public static final int type_letter_only = 1;
/**
* The verification code is composed of numbers, uppercase letters, and lowercase letters.
*/
Public static final int type_all_mixed = 2;
/**
* The verification code is composed of numbers and uppercase letters.
*/
Public static final int type_num_upper = 3;
/**
* The verification code is composed of numbers and lowercase letters.
*/
Public static final int type_num_lower = 4;
/**
* The verification code type is uppercase letters only.
*/
Public static final int type_upper_only = 5;
/**
* The verification code type is only lowercase letters.
*/
Public static final int type_lower_only = 6;
Private verifycode (){
}
/**
* Generate a verification code string
*
* @ Param type
* For the verification code type, see static attributes of this class.
* @ Param Length
* Verification code length, an integer greater than 0
* @ Param exChars
* Special characters to be excluded (only valid for mixed verification codes of numbers and letters, and null if not excluded)
* @ Return verification code string
*/
Public static String generateTextCode (int type, int length, String exChars ){
If (length <= 0)
Return "";
StringBuffer code = new StringBuffer ();
Int I = 0;
Random r = new Random ();
Switch (type ){
// Only number
Case type_num_only:
While (I <length ){
Int T = R. nextint (10 );
If (exchars = NULL | exchars. indexof (t + "") <0) {// exclude special characters
Code. append (t );
I ++;
}
}
Break;
// Only letters (uppercase letters and lowercase letters)
Case TYPE_LETTER_ONLY:
While (I <length ){
Int t = r. nextInt (123 );
If (t> = 97 | (t> = 65 & t <= 90) & (exChars = null | exChars. indexOf (char) t) <0 )){
Code. append (char) t );
I ++;
}
}
Break;
// A mix of numbers, uppercase letters, and lowercase letters
Case TYPE_ALL_MIXED:
While (I <length ){
Int t = r. nextInt (123 );
If (t> = 97 | (t> = 65 & t <= 90) | (t> = 48 & t <= 57 )) & (exChars = null | exChars. indexOf (char) t) <0 )){
Code. append (char) t );
I ++;
}
}
Break;
// Mixed numbers and uppercase letters
Case TYPE_NUM_UPPER:
While (I <length ){
Int t = r. nextInt (91 );
If (t> = 65 | (t> = 48 & t <= 57) & (exChars = null | exChars. indexOf (char) t) <0 )){
Code. append (char) t );
I ++;
}
}
Break;
// Mix digits and lowercase letters
Case TYPE_NUM_LOWER:
While (I <length ){
Int t = r. nextInt (123 );
If (t> = 97 | (t> = 48 & t <= 57) & (exChars = null | exChars. indexOf (char) t) <0 )){
Code. append (char) t );
I ++;
}
}
Break;
// Only uppercase letters
Case TYPE_UPPER_ONLY:
While (I <length ){
Int t = r. nextInt (91 );
If (t> = 65) & (exChars = null | exChars. indexOf (char) t) <0 )){
Code. append (char) t );
I ++;
}
}
Break;
// Only lowercase letters
Case TYPE_LOWER_ONLY:
While (I <length ){
Int T = R. nextint (123 );
If (T> = 97) & (exchars = NULL | exchars. indexof (char) T) <0 )){
Code. append (char) t );
I ++;
}
}
Break;
}
Return code. tostring ();
}
/**
* If a verification code already exists, a verification code image is generated.
*
* @ Param textCode
* Text Verification Code
* @ Param width
* Image Width
* @ Param height
* Image Height
* @ Param interLine
* Number of interference lines in the image
* @ Param randomLocation
* Are the high and low positions of each character random?
* @ Param backColor
* The image color. If it is null, a random color is used.
* @ Param foreColor
* Font color. If it is null, a random color is used.
* @ Param lineColor
* Interference line color. If it is null, a random color is used.
* @ Return: Image cache object
*/
Public static BufferedImage generateImageCode (String textCode, int width, int height, int interLine, boolean randomLocation, Color backColor,
Color foreColor, Color lineColor ){
BufferedImage bim = new BufferedImage (width, height, BufferedImage. TYPE_INT_RGB );
Graphics g = bim. getGraphics ();
// Draw the background image
G. setColor (backColor = null? GetRandomColor (): backColor );
G. fillRect (0, 0, width, height );
// Draw interference lines
Random r = new Random ();
If (interLine> 0 ){
Int x = 0, y = 0, x1 = width, y1 = 0;
For (INT I = 0; I <interline; I ++ ){
G. setcolor (linecolor = NULL? Getrandomcolor (): linecolor );
Y = R. nextint (height );
Y1 = R. nextint (height );
G. drawline (X, Y, X1, Y1 );
}
}
// Write the verification code
// G. setcolor (getrandomcolor ());
// G. setColor (isSimpleColor? Color. BLACK: Color. WHITE );
// The font size is 80% of the Image Height.
Int fsize = (int) (height * 0.8 );
Int fx = height-fsize;
Int fy = fsize;
G. setFont (new Font (Font. DIALOG, Font. PLAIN, fsize ));
// Write Verification Code characters
For (int I = 0; I <textCode. length (); I ++ ){
Fy = randomLocation? (Int) (Math. random () * 0.3 + 0.6) * height): fy; // whether each character is random
G. setColor (foreColor = null? GetRandomColor (): foreColor );
G. drawstring (textcode. charat (I) + "", FX, FY );
FX + = fsize * 0.9;
}
G. Dispose ();
Return Bim;
}
/**
* Generate an image Verification Code
*
* @ Param type
* For the verification code type, see static attributes of this class.
* @ Param Length
* Verification Code character length, an integer greater than 0
* @ Param exchars
* Special characters to be excluded
* @ Param width
* Image Width
* @ Param height
* Image Height
* @ Param interLine
* Number of interference lines in the image
* @ Param randomLocation
* Are the high and low positions of each character random?
* @ Param backColor
* The image color. If it is null, a random color is used.
* @ Param foreColor
* Font color. If it is null, a random color is used.
* @ Param lineColor
* Interference line color. If it is null, a random color is used.
* @ Return: Image cache object
*/
Public static BufferedImage generateImageCode (int type, int length, String exChars, int width, int height, int interLine, boolean randomLocation,
Color backColor, Color foreColor, Color lineColor ){
String textCode = generateTextCode (type, length, exChars );
BufferedImage bim = generateImageCode (textCode, width, height, interLine, randomLocation, backColor, foreColor, lineColor );
Return bim;
}
/**
* Generate random colors
*
* @ Return
*/
Private static Color getRandomColor (){
Random r = new Random ();
Color c = new Color (r. nextInt (255), r. nextInt (255), r. nextInt (255 ));
Return c;
}
Public static void main (String [] args ){
}
}
3.org. javachina. servlet. verifycodeservlet. Java
Package org. javachina. servlet;
Import java. awt. Color;
Import java. awt. image. BufferedImage;
Import java. io. IOException;
Import javax. imageio. ImageIO;
Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Import org. javachina. util. VerifyCode;
Public class VerifyCodeServlet extends HttpServlet {
Public VerifyCodeServlet (){
Super ();
}
Public void destroy (){
Super. destroy ();
}
Public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Set the browser to not cache this page
Response. setHeader ("Cache-Control", "no-cache ");
// Generate a verification code and write it to the user session
String verifyCode = VerifyCode. generateTextCode (VerifyCode. TYPE_UPPER_ONLY, 4, null );
Request. getSession (). setAttribute ("verifyCode", verifyCode );
// Output the verification code to the client
Response. setContentType ("image/jpeg ");
BufferedImage bim = VerifyCode. generateImageCode (verifyCode, 60, 20, 3, true, Color. WHITE, Color. BLACK, null );
ImageIO. write (bim, "JPEG", response. getOutputStream ());
}
Public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
Public void init () throws ServletException {
}
}
4.org. javachina. servlet. pubmsgservlet. Java
Package org. javachina. servlet;
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 PubMsgServlet extends HttpServlet {
Public PubMsgServlet (){
Super ();
}
Public void destroy (){
Super. destroy (); // Just puts "destroy" string in log
// Put your code here
}
Public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Obtain the message title, content, and verification code entered by the user
String msgTitle = request. getParameter ("msgTitle ");
String msgContent = request. getParameter ("msgContent ");
String verifyCode = request. getParameter ("verifyCode ");
// Obtain the correct verification code in the session
String legalCode = null;
If (request. getSession (). getAttribute ("verifyCode ")! = Null)
LegalCode = (String) (request. getSession (). getAttribute ("verifyCode "));
String next;
// Compare whether the verification code in the session is consistent with the user input (case-insensitive)
If (verifyCode! = Null & verifyCode. inclusignorecase (legalCode )){
/*
* Save the message content (omitted)
*/
// Specify the next URL
Next = request. getContextPath () + "/OK. jsp ";
} Else
Next = "this ";
Response. setContentType ("text/plain ");
PrintWriter out = response. getWriter ();
Out. print (next );
Out. flush ();
Out. close ();
}
Public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
Public void init () throws ServletException {
}
}
5. OK. jsp
<% @ Page language = "java" import = "java. util. *" pageEncoding = "gbk" %>
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Body>
Your message has been submitted! <Input type = "button" value = "OK" onClick = "window. history. go (-1)"/> <br>
</Body>
</Html>
6. modify web. XML to add the following content:
<Servlet>
<Servlet-name> VerifyCodeServlet </servlet-name>
<Servlet-class> org. javachina. servlet. VerifyCodeServlet </servlet-class>
</Servlet>
<Servlet>
<Servlet-name> PubMsgServlet </servlet-name>
<Servlet-class> org. javachina. servlet. PubMsgServlet </servlet-class>
</Servlet>
<Servlet-mapping>
<Servlet-name> VerifyCodeServlet </servlet-name>
<Url-pattern>/servlet/VerifyCodeServlet </url-pattern>
</Servlet-mapping>
<Servlet-mapping>
<Servlet-name> PubMsgServlet </servlet-name>
<URL-pattern>/servlet/pubmsgservlet </url-pattern>
</Servlet-mapping>
Reprint address: http://www.java3z.com/cwbwebhome/article/article3/3468.html? Id = 2132