第一步:
首先先写一个验证码图片生成类CreateAuthCode
package com.sunsheng.commons;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
public class CreateAuthCode extends BufferedImage {
private Graphics graphics;
private int width;
private int height;
public CreateAuthCode(int width, int height, int imageType) {
super(width, height, imageType);
this.width = width;
this.height = height;
graphics = getGraphics();
//设置图片的背景颜色
setBgColor();
//给图片设置一个边框
setBorder();
//往图片中写入字符串
setText();
}
private void setBorder() {
//设置边框的颜色
graphics.setColor(Color.RED);
//为了防止边框写到图片外面,所以处理一下
graphics.drawRect(1, 1, width - 2, height - 2);
}
private void setBgColor() {
graphics.setColor(Color.WHITE);
//往矩形区域填充设置的颜色
graphics.fillRect(0, 0, width, height);
}
private void setText() {
graphics.setColor(Color.BLUE);
//设置文件的字体
graphics.setFont(new Font("宋体", Font.BOLD, 60));
// graphics.drawString("中国", 10, 80);
int x = 10;
//往图片中写入4个随机的整数(0~9)
for (int i = 0; i < 4; i++) {
int num = new Random().nextInt(10);
//坐标是字符串左下角的那个点
graphics.drawString(String.valueOf(num), x, 65);
//数字字符串是半角格式占30个像素,每个字符串之间距离10个像素,所以x轴要右移40像素
x += 40;
}
}
}
第二步:
在Servlet中输入图片
package com.sunsheng;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sunsheng.commons.CreateAuthCode;
public class AuthCode extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//设置http响应头,告诉浏览器服务器发送的是一个jpeg格式的图片
resp.setHeader("content-type", "image/jpeg");
//在内存中创建一个图片
//调用ImageIO工具的write方法把图片从内存写到Response的OutputStream中
ImageIO.write(new CreateAuthCode(180, 80, BufferedImage.TYPE_INT_RGB)
, "jpg"
, resp.getOutputStream());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}