在servlet中生成随机验证码:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//禁止页面缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
int width=60;
int height=20;
/**
 * 创建一个位于缓存中的图像。
 * */
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();//获取用于处理图形上下文的对象,相当于画笔
Random random = new Random();//生成随机数
g.setColor(getRandomColor(200, 250));//设置图像背景色
g.fillRect(0, 0, width, height);//画一个矩形,坐标0,0,
g.setFont(new Font("Time New Roman", Font.PLAIN, 18));//设置字体格式
g.setColor(getRandomColor(160, 200));
for (int i = 0; i < 130; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(12);
int y1 = random.nextInt(12);
g.drawLine(x, y,x+x1, y+y1);
}
String strCode = "";
for (int i = 0; i < 4; i++) {
String strNumber = String.valueOf(random.nextInt(10));
strCode = strCode + strNumber;
//设置字体颜色
g.setColor(new Color(15+random.nextInt(120),15+random.nextInt(120),15+random.nextInt(120)));
g.drawString(strNumber, 13*i+6, 16);//将验证码依次画到图像上,坐标(13*i+6, 16)
}
request.getSession().setAttribute("strCode", strCode);//将验证码保存到Session中
g.dispose();//释放g的所有资源
ImageIO.write(image, "jpeg", response.getOutputStream());//输出
response.getOutputStream().flush();
response.getOutputStream().close();
}