public class ResponseYan extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.如何让浏览器三秒刷新一次
resp.setHeader("refresh","3");
//2.在内存中创建一个图片
BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
//3.得到照片
Graphics2D pan = (Graphics2D) image.getGraphics();
//4.设置照片的背景颜色
pan.setColor(Color.blue);
pan.setFont(new Font(null,Font.BOLD,20));
//5.给照片写数据
pan.setColor(Color.blue);
pan.setFont(new Font(null,Font.BOLD,20));
pan.drawString(makeNum(),0,20);
//6.告诉浏览器,这个请求用图片打开
resp.setContentType("image/jpeg");
//7.网站存在缓存,不让浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-chche");
//8.把照片写给浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
}
private String makeNum(){
Random ran = new Random();
//int加上空字符串就变成字符串类型
String s = ran.nextInt(9999999)+"";
StringBuffer sb = new StringBuffer();
for(int i = 0;i <7-s.length(); i++){
sb.append("0");
}
s = sb.toString()+s;
return s;
}
运行结果: