The code looks like this:
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 class
* @projectNetWorkService
* @package com.hoo.util
* @fileName ValidCodeUtils.java
* @createDate 2010-8-3 03:05:50 PM
*@authorhoojo
*/
@SuppressWarnings("unused")
public class ValidCodeUtils {
/****************************************************** *********************
* Verification code width
*/
public static int WIDTH = 60;
/***
* Verification code height
*/
public static int HEIGHT = 20;
/****************************************************** *********************
* The background color of the verification code COLOR_FC_BG should be smaller than COLOR_BC_BG
*/
public static int COLOR_FC_BG = 200;
/***
* The background color of the verification code 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 within the specified range
* @param fc range fc color value is less than 255
* @param bc range bc color value is less than 255
* @returnColor
*/
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> Generate image method
* @createDate 2010-8-3 03:06:22 PM
*@authorhoojo
* @param request HttpServletRequest
* @param response HttpServletResponse
* @return boolean
* @throwsException
*/
public static boolean getImage(HttpServletRequest request, HttpServletResponse response) throws Exception{
response.reset();
response.setContentType("image/jpeg");
//Set the page not to be cached
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
//Create image in memory
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
// Get graphics context
Graphics img = image.getGraphics();
// Generate random class
Random random = new Random();
//Set background color
img.setColor(getRandColor(COLOR_FC_BG, COLOR_BC_BG));
img.fillRect(0, 0, WIDTH, HEIGHT);
//Set font
img.setFont(new Font("Times New Roman", Font.PLAIN, 18));
// draw borders
// g.setColor(new Color());
// g.drawRect(0,0,width-1,height-1);
// Randomly generate 155 interference lines to make the authentication code in the image difficult 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);
}
// Get the randomly generated authentication 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 into the image
img.setColor(getRandColor(COLOR_FC_CODE, COLOR_BC_CODE));
img.drawString(rand, 13 * i + 6, 16);
}
request.getSession().setAttribute("codeValue", codeValue);
//image takes effect
img.dispose();
// Output the image to the page
return ImageIO.write(image, "JPEG", response.getOutputStream());
}
/**
* Randomly generate characters, including uppercase, lowercase, and numbers
* <b>function:</b> function
* @createDate 2010-8-23 10:33:55 AM
*@authorhoojo
* @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> Randomly generate fonts and text sizes
* @createDate 2010-8-23 10:44:22 AM
*@authorhoojo
* @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 value of the verification code is stored in the session: request.getSession().setAttribute("codeValue", codeValue);
Just compare the value entered by the user and the codeValue in the session to see if they are equal;
The following is the jsp page calling servlet: ValidCodeServlet.java
The above ValidCodeUtils verification code generation tool class is called in ValidCodeServlet
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);
}
}
Just call the servlet method on the jsp page
js: reloadValidCode method
function reloadValidCode(o) {
o.src = "${pageContext.request.contextPath }/validCodeServlet?timed=" + new Date().getMilliseconds();
}
The "timed=" + new Date().getMilliseconds(); here is needed to prevent IE caching.
html tag:
<img src="${pageContext.request.contextPath }/validCodeServlet" onclick="reloadValidCode(this)"/>
Just configure the URL directly with the Servlet name, which corresponds to the web.xml configuration. The main calling path ${pageContext.request.contextPath}/validCodeServlet will bring the root directory, which is safer.
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>