import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如何让浏览器五秒自动刷新一次
resp.setHeader("refresh","5");
//在内存中创建一个图片
BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
//得到图片
Graphics2D g = (Graphics2D) image.getGraphics(); //笔
//设置背景颜色
g.setColor(Color.white);
g.fillRect(0,0,80,20); //填充
// 给图片写数据
g.setColor(Color.BLUE); //用蓝色写
g.setFont(new Font(null,Font.BOLD,20));
g.drawString(makeNum(),0,20);
//告诉浏览器,这个请求用图片的方式打开
resp.setContentType("image/jpeg");
//网站存在缓存,此操作不让网站缓存
resp.setDateHeader("expirse",-1);
resp.setHeader("Cache-control","no-cache");
resp.setHeader("Pragme","no-cache");
//把图片写给浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
}
//生成随机数
public String makeNum(){
Random random = new Random();
String num = random.nextInt(99999)+ "";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 5 - num.length(); i++) {
sb.append("0"); //不足五位用0填充
}
num = num + sb.toString();
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
JavaWeb写验证码
最新推荐文章于 2022-04-15 16:23:06 发布
该博客介绍了一个Servlet实现方法,它能在服务器端生成包含随机数字的JPEG图片,并设置响应头使得浏览器每5秒自动刷新一次。通过内存中创建BufferedImage对象,设置颜色、字体,然后使用Graphics2D绘制随机数,最后将图片输出到HTTP响应中,防止浏览器缓存。
摘要由CSDN通过智能技术生成