public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static int I_WIDTH = 60;
private static int I_HEIGHT = 18;
private static Font VALIDATECODE_FONT = new Font("Times New Roman",
Font.PLAIN, 18);
public ImageServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 在内存中创建图象
BufferedImage image = new BufferedImage(I_WIDTH, I_HEIGHT,
BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
// 设定背景色
g.setColor(Color.white);
g.fillRect(0, 0, I_WIDTH, I_HEIGHT);
// 画边框
g.setColor(Color.blue);
g.drawRect(0, 0, I_WIDTH - 1, I_HEIGHT - 1);
Long validate = new Long(10000 + Math.round((Math.random() * 90000)));
String validateCode = validate.toString();
request.getSession().setAttribute("validateCode", validateCode);
// 将认证码显示到图象中
g.setColor(Color.black);
g.setFont(VALIDATECODE_FONT);
// g.drawString(rand,10,15);
g.drawString(validateCode.toString(), 7, 15);
// 随机产生88个干扰点,使图象中的认证码不易被其它程序探测到
Random random = new Random();
for (int iIndex = 0; iIndex < 128; iIndex++) {
int x = random.nextInt(I_WIDTH);
int y = random.nextInt(I_HEIGHT);
g.drawLine(x, y, x, y);
}
// 图象生效
g.dispose();
// 输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());
System.out.println("=============================================");
}
}
想了一会儿,还没想到一个合理的解释的方法。
--------------------编程问答--------------------
en ,我也遇到过,如果是通过页面引用该servlet就不会出现调用两次的现象。。
--------------------编程问答--------------------