标签:
public class CodeServlet extends HttpServlet {
 /**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
response.setContentType("image/jpeg");
		// 创建图片缓冲流
		int width = 90; // 宽度
		int height = 25; // 高度
		int imageType = BufferedImage.TYPE_INT_RGB; // 颜色
		BufferedImage image = new BufferedImage(width, height, imageType);
		// 获取缓冲图片流中的画布
		Graphics g = image.getGraphics();
		// 设置画笔的颜色
		g.setColor(Color.lightGray);
		// 填充画布区域
		g.fillRect(0, 0, width, height);
		// 输出的内容
		String word = "abcdefhijklmnopqrstuvwxyz";
		// 将要输出的内容,转换为 字节数组
		char[] words = word.toCharArray();
		// 定义一个随机对象
		Random random = new Random();
String sessionWord = "";
		for (int i = 0; i < 4; i++) {
			String temp = words[random.nextInt(words.length)] + "";
			sessionWord += temp;
			// 更改画笔的颜色
			g.setColor(new Color(random.nextInt(255), random.nextInt(255),
					random.nextInt(255)));
			g.setFont(new Font("微软雅黑", Font.BOLD, 20));
			// 使用画笔,在画布上写字
			g.drawString(temp, 20 * i + 10, 20);
		}
request.getSession().setAttribute("code", sessionWord);
		// 获取servlet 输出流
		OutputStream output = response.getOutputStream();
		// 图片io流
		ImageIO.write(image, "jpeg", output);
}
}
标签:
原文地址:http://www.cnblogs.com/zhangliang88/p/5330350.html