日期:2014-05-16  浏览次数:20412 次

JSP制作简单“验证码”

用JSP写个简单的“验证码”

?

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="java.awt.image.BufferedImage"%>
<%@page import="java.awt.Graphics"%>
<%@page import="java.awt.Color"%>
<%@page import="java.io.OutputStream"%>
<%@page import="com.sun.image.codec.jpeg.JPEGImageEncoder"%>
<%@page import="com.sun.image.codec.jpeg.JPEGCodec"%>
<%@page import="java.awt.Font"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";

	char[] mapTable = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
			'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
			'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7',
			'8', '9' };

	// 取随机产生的认证码  
	String strEnsure = "";

	// 4代表4位验证码  
	for (int i = 0; i < 4; ++i) {
		strEnsure += mapTable[(int) (mapTable.length * Math.random())];
	}
	session.setAttribute("strEnsure", strEnsure);

	response.setContentType("image/jpeg");
	// 图片的内存映像
	BufferedImage image = new BufferedImage(70, 24,
			BufferedImage.TYPE_INT_RGB);
	Random r = new Random();
	// 获得画笔对象
	Graphics g = image.getGraphics();
	g
			.setColor(new Color(r.nextInt(255), r.nextInt(255), r
					.nextInt(255)));
	g.fillRect(0, 0, 70, 24);
	g.setColor(new Color(0, 0, 0));
	g.setFont(new Font("Atlantic Inline", Font.PLAIN, 18));

	g.drawString(strEnsure, 11, 18);

	g.drawLine(r.nextInt(60), r.nextInt(20), r.nextInt(60), r
			.nextInt(20));
	// 压缩成jpeg格式
	OutputStream os = response.getOutputStream();
	JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
	// 把BufferedImage对象中的图像信息编码后
	// 向创建该对象(encoder)时指定的输出流输出
	encoder.encode(image);
	out.clear();
	out = pageContext.pushBody();
%>

?