在登录模块中经常要使用到验证码机制来防止破坏者恶意注册及登录,在此留一份备份以备日后回忆。
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 java.util.Random;
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;
@SuppressWarnings("serial")
public class ImageCaptchaServlet extends HttpServlet {
private static final int WIDTH = 72;
private static final int HEIGHT = 30;
private static final int NUM = 4;
private static final String CODES = "0123456789";
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
// 获取会话Session
HttpSession session = request.getSession();
// 设置缓存及响应类型
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
// 创建一张图片
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// 设置白色背景
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
// 画边框
g.setColor(new Color(0xC1C1C1));
g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);
// 画干扰点
Random random = new Random();
for (int i = 0; i < 100; i++) {
g.setColor(new Color(0xC1C1C1));
g.drawOval(random.nextInt(WIDTH), random.nextInt(HEIGHT), 1, 1);
}
// 生成随机函数
char[] rand = new char[NUM];
for (int i = 0; i < NUM; i++) {
rand[i] = CODES.charAt(random.nextInt(CODES.length()));
}
String code = new String(rand);
// 显示验证码显示的样式
g.setFont(new Font("Consolas", Font.BOLD, 30));
g.setColor(new Color(0x999999));
// 显示验证码
g.drawString(code, 2, 25);
// 生成图片
g.dispose();
// 设置响应大小
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ImageIO.write(image, "JPEG", byteOut);
byte[] buffer = byteOut.toByteArray();
response.setContentLength(buffer.length);
// 输出给浏览器
ServletOutputStream out = response.getOutputStream();
out.write(buffer);
// 关闭输出流
byteOut.close();
out.close();
//把验证码写入Session
session.setAttribute("check_code", code);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
doGet(request, response);
}
}
分享到:
评论