1、生成图片用到的类
(1)BufferedImage图像数据缓冲区。
(2)Graphics绘制图片
(3)Color获得颜色
(4)Random生成随机数
(5)ImageIO输出图片
2、生成图片的步骤
2-1、 生成图片的实现类(创建ImageServlet类)
(1)定义BufferedImage对象
(2)获得Graphics对象
(3)通过Random产生随机验证码信息
(4)使用Graphics绘制图片
(5)记录验证码信息到session中
(6)使用ImageIO输出图片
2-2、校验验证码是否正确(LoginServlet类)
(1)获取页面验证码
(2)获取session保存的验证码
(3)比较验证码
(4)返回校验结果
3、源代码
3-1、生成图片的类
package com.caokaiyuan.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class CheckCodeServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
<