servlet实现验证码

<1>image.do的servlet实现画出含有四个字符的图片:
public class ImageServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedImage image = new BufferedImage(80, 25,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.BLUE);
g.fillRect(0, 0, 80, 25);
String[] vs = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "A","a",
"g", "G", "f", "F", "e", "E", "d", "D", "c", "C", "b","z",
  "B", "H", "h", "I", "i", "J", "j", "K", "k", "L", "l", "M",
  "m", "N", "n", "O", "o", "P", "p", "Q", "q", "R", "r", "S",
  "s", "T", "t", "U", "u", "V", "v", "W", "w", "X", "x", "Y",
  "y", "Z" };
g.setFont(new Font("Serif", Font.BOLD, 18));
StringBuffer sb = new StringBuffer();
for (int i = 0, x = 10, y = 18; i < 4; i++) {
g.setColor(getRandomColor());
String t = vs[(int) (Math.random() * vs.length)];
g.drawString(t, x, y);
sb.append(t);
x = x + 13;
}
g.dispose();
response.setContentType("image.jpeg");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-control", "no-cache");
response.setDateHeader("Expires", 0);
String v = sb.toString();
HttpSession session = request.getSession();
session.setAttribute("v", v);
OutputStream os = response.getOutputStream();
ImageIO.write(image, "jpeg", os);
os.flush();
os.close();
}
private Color getRandomColor() {
Random random = new Random();
int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
return new Color(r, g, b);
}
}
<2>在jsp中调用:
<img alt="验证码" src="image.do">
<a href="login.jsp"><font size="2" color="green">看不清楚,换一张</font></a>

你可能感兴趣的:(c,jsp,servlet,cache,OS)