废话不说 直接进入代码区: private static final String CHARARRAY[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "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" }; private String getRandChar(int randNumber) return CHARARRAY[randNumber]; } private Color getRandColor(int fc, int bc) { Random random = new Random(); if (fc > 255) fc = 255; if (bc > 255) bc = 255; 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); } Servlet中的doPost方法如下: response.setContentType("image/ipeg");// 设置响应内容的类型 response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0L);// 设置响应头信息 int width = 60;// 图片宽度 int height = 20; BufferedImage image = new BufferedImage(width, height, 1);// 以给定的变量定义图片 Graphics g = image.getGraphics();// 得到图片背景 Random random = new Random(); g.setColor(getRandColor(200, 2500));// 自定义颜色 g.fillRect(0, 0, width, height);// 使用自定义颜色填充图片背景 g.setFont(new Font("Arial", 0, 19));// 设置图片中字体 g.setColor(getRandColor(160, 200));// 自定义颜色 String sRand = ""; for (int i = 0; i < 4; i++) { String rand = getRandChar(random.nextInt(36));// 从给定的数组中产生随机数 sRand = sRand + rand; g.setColor(new Color(20 + random.nextInt(110), 20 + random .nextInt(110), 20 + random.nextInt(110)));// 设置字符串的随机颜色 g.drawString(rand, 13 * i + 6, 16);// 将文本放入图片中 } request.getSession().setAttribute("rand", sRand); g.dispose();// 将图片做成对象 ServletOutputStream imageOut = response.getOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(imageOut); encoder.encode(image);// 将图像放入响应中 完成上边儿的 在web.xml下配置一下 就可以直接在 登录页面显示验证码啦...