【Servlet】产生验证码

ImageServlet.java

package yzm;

import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;

import java.io.*;
import java.util.Random;
import javax.servlet.*;
import javax.servlet.http.*;

public class ImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置页面不缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		// 在内存中创建图象
		int width = 60, height = 20;
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		// 获取图形上下文
		Graphics g = image.getGraphics();
		// 创建随机数对象
		Random random = new Random();
		// 设定背景色
		g.setColor(new Color(122, 123, 100));
		g.fillRect(0, 0, width, height);
		// 设定字体
		g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
		// 随机产生干扰线,使图象中的认证码不易被其它程序探测到
		for (int i = 0; i < 200; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}
		// 取随机产生的认证码(4位数字)

		String sRand = "";
		for (int i = 0; i < 4; i++) {
			String rand = String.valueOf(random.nextInt(10));
			sRand += rand;
			// 将认证码显示到图象中
			g.setColor(new Color(30 + random.nextInt(160), 40 + random
					.nextInt(170), 40 + random.nextInt(180)));
			g.drawString(rand, 13 * i + 6, 16);
		}
		// 将认证码存入SESSION
		request.getSession().setAttribute("yzm", sRand);
		g.dispose();
		// 输出图象到页面
		ImageIO.write(image, "JPEG", response.getOutputStream());
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}

web.xml

	
	
		ImageServlet
		yzm.ImageServlet
	
	
		ImageServlet
		/servletyzm
	


jsp页面调用

	验证码




你可能感兴趣的:(JavaWeb)