java-web绘制验证码图片例程

页面html代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	function changeImage() {
		document.getElementById("randomCode").src = "/randomCode?"
				+ Math.random();解决点击验证码没有反应问题
	}
</script>
</head>
<body>
	<form action="/login" method="post">
		用户名:<input name="username" type="text"><br /> 密码:<input
			name="password" type="password"><br /> 验证码:<input name="code"
			type="text"><img alt="" src="/randomCode" id="randomCode"
			style="cursor: pointer;" onclick="changeImage()"> ${error}<br />
		<input type="submit" value="登录">
	</form>
</body>
</html>


 

java代码:

package test.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

public class LoginServlet extends HttpServlet {
	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String code = request.getParameter("code");
		String randomCode = (String) request.getSession().getAttribute(
				"randomCode");
		if (StringUtils.equalsIgnoreCase(code, randomCode)) {
			System.out.println("执行正常的业务逻辑");
		} else {
			request.setAttribute("error", "验证码出错");
			request.getRequestDispatcher("/login.jsp").forward(request,
					response);
		}
	}

}

package test.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class RandomCodeServlet
 */
public class RandomCodeServlet extends HttpServlet {
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String randomCode = (UUID.randomUUID().toString()).substring(0, 4);
		request.getSession().setAttribute("randomCode", randomCode);

		response.setContentType("image/jpeg"); // 因为向客户端发送的内容是图片. 所以用这种内容类型

		int width = 100;
		int height = 50;
		// 1.创建一个图片对象
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_BGR);

		// 2.得到画布
		Graphics graphics = image.getGraphics();

		// 3.开始在图片上画画

		// 3.1 用白色填充. 首先要设置上下文的颜色
		graphics.setColor(Color.white);// 设置白色
		graphics.fillRect(1, 1, width - 2, height - 2);

		// 3.2 用黑色写文字
		graphics.setColor(Color.black);
		graphics.setFont(new Font("宋体", Font.BOLD, 30));
		graphics.drawString(randomCode, width / 6, height / 2 + 5);

		// 3.3 画混淆内容
		graphics.setColor(Color.red);
		for (int i = 0; i < 50; i++) {
			graphics.fillOval(new Random().nextInt(width),
					new Random().nextInt(height), 3, 3);
		}
		for (int i = 0; i < 10; i++) {
			graphics.setColor(new Color[] { Color.red, Color.blue, Color.GRAY }[new Random()
					.nextInt(3)]);
			graphics.drawLine(new Random().nextInt(width),
					new Random().nextInt(height), new Random().nextInt(width),
					new Random().nextInt(height));
		}

		// 4.关闭画布,释放资源...
		graphics.dispose();
		// 输出图片

		ImageIO.write(image, "JPG", response.getOutputStream());
	}

}

你可能感兴趣的:(graphics,graphics,ImageIO,java画图,验证码绘制)