@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//让浏览器0.01秒自动刷新一次
resp.setHeader("refresh","0.01");
BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_BGR);
//生成一只画笔
Graphics2D graphics = (Graphics2D) image.getGraphics();
//给画笔添加颜色
graphics.setColor(Color.white);
//设置绘制大小
graphics.fillRect(0,0,80,20);
//改变画笔颜色,准备写字了
graphics.setColor(Color.BLACK);
//设置画笔样式
graphics.setFont(new Font(null,Font.BOLD,20));
//随机生成六位数的验证码
graphics.drawString(makeNum(),0,20);
resp.setContentType("image/png");
resp.setDateHeader("expires",-1);
//控制浏览器不要缓存图片
resp.setHeader("Cache-Control","no-catch");
ImageIO.write(image,"png",resp.getOutputStream());
}
private String makeNum(){
Random random = new Random();
String num = random.nextInt(999999)+"";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 7-num.length(); i++) {
sb.append("0");
}
num = sb.toString()+num;
return num;
}
Java语言写验证码
最新推荐文章于 2024-10-30 23:38:42 发布