1 <%@ page contentType="text ml;charset=UTF-8" language="java"%>
2 <%@ page import="java.awt.*"%>
3 <%@ page import="java.awt.image.*"%>
4 <%@ page import="java.util.*"%>
5 <%@ page import="javax.imageio.*"%>
6
7 <%!Color getRandColor(int fc, int bc) {
8 Random random = new Random();
9 if (fc > 255)
10 fc = 255;
11 if (bc > 255)
12 bc = 255;
13 int r = fc + random.nextInt(bc - fc);
14 int g = fc + random.nextInt(bc - fc);
15 int b = fc + random.nextInt(bc - fc);
16 return new Color(r, g, b);
17 }%>
18 <%
19 response.setHeader("Pragma", "No-cache");
20 response.setHeader("Cache-Control", "no-cache");
21 response.setDateHeader("Expires", 0);
22 int width = 60;
23 int height = 20;
24 BufferedImage image = new BufferedImage(width, height,
25 BufferedImage.TYPE_INT_RGB);
26 Graphics g = image.getGraphics();
27 Random random = new Random();
28 g.setColor(getRandColor(200, 250));
29 g.fillRect(0, 0, width, height);
30 g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
31 g.setColor(getRandColor(160, 200));
32 for (int i = 0; i < 155; i++) {
33 int x = random.nextInt(width);
34 int y = random.nextInt(height);
35 int x1 = random.nextInt(12);
36 int y1 = random.nextInt(12);
37 g.drawLine(x, y, x + x1, y + y1);
38 }
39 String sRand = "";
40 for (int i = 0; i < 4; i++) {
41 String rand = String.valueOf(random.nextInt(10));
42 sRand += rand;
43 g.setColor(new Color(20 + random.nextInt(110), 20 + random
44 .nextInt(110), 20 + random.nextInt(110)));
45 g.drawString(rand, 13 * i + 6, 16);
46 }
47 // 将验证码保存到session中,登录验证时再取出和用户输入的进行比较
48 session.setAttribute("checkCode", sRand);
49 g.dispose();
50 ImageIO.write(image, "JPEG", response.getOutputStream());
51 out.clear();
52 out = pageContext.pushBody();
53 %>