1 package com.helloweenvsfei.servlet;
2
3 import java.awt.Color;
4 import java.awt.Font;
5 import java.awt.Graphics2D;
6 import java.awt.image.BufferedImage;
7 import java.io.IOException;
8 import java.util.Random;
9
10 import javax.servlet.ServletException;
11 import javax.servlet.ServletOutputStream;
12 import javax.servlet.http.HttpServlet;
13 import javax.servlet.http.HttpServletRequest;
14 import javax.servlet.http.HttpServletResponse;
15
16 import com.sun.image.codec.jpeg.JPEGCodec;
17 import com.sun.image.codec.jpeg.JPEGImageEncoder;
18
19 public class IdentityServlet extends HttpServlet{
20 public static final char[] CHARS={
21 '2', '3', '4', '5', '6', '7', '8',
22 '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
23 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
24 };
25 public static Random random =new Random();
26
27 public static String getRandomString(){
28 StringBuffer buffer=new StringBuffer();
29 for(int i=0;i<6;i++){
30 buffer.append(CHARS[random.nextInt(CHARS.length)]);
31 }
32 return buffer.toString();
33
34 }
35 public static Color getRandomColor() {
36 return new Color(random.nextInt(255), random.nextInt(255), random
37 .nextInt(255));
38 }
39
40 public static Color getReverseColor(Color c) {
41 return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c
42 .getBlue());
43 }
44 public void doGet(HttpServletRequest request,HttpServletResponse response)
45 throws ServletException, IOException {
46 response.setContentType("image/jpeg");
47 String randomString = getRandomString();
48 request.getSession(true).setAttribute("randomString", randomString);
49
50 int width = 100;
51 int height = 30;
52
53 Color color = getRandomColor();
54 Color reverse = getReverseColor(color);
55 BufferedImage bi = new BufferedImage(width, height,
56 BufferedImage.TYPE_INT_RGB);
57 Graphics2D g = bi.createGraphics();
58 g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));
59 g.setColor(color);
60 g.fillRect(0, 0, width, height);
61 g.setColor(reverse);
62 g.drawString(randomString, 18, 20);
63 for (int i = 0, n = random.nextInt(100); i < n; i++) {
64 g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);
65 }
66
67 // 转成JPEG格式
68 ServletOutputStream out = response.getOutputStream();
69 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
70 encoder.encode(bi);
71 out.flush();
72 }
73
74 public static void main(String[] args) {
75 System.out.println(getRandomString());
76 }
77 }