Servlet学习之⽣成随机数
令页⾯⽣成⼀个每五秒产⽣⼀个数字的动态图
package com.servlet.demo
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 DrawDemo extends HttpServlet{
protected void doGet(HttpServletResquest req,HttpServletResponse resp)throws ServletException, IOException{ //设置刷新时间,单位为秒
resp.setHeader("refresh","5");
//在内存中创建⼀个图⽚
BufferImage image=new BuffferImage(200,80,BufferImage.TYPE_INT_RGB);
//获得图⽚
Graphics2D gd=(Graphics();//相当于画笔
//设置图⽚背景⾊
gd.setColor(Color.BLUE);
gd.setFont(null,Font.BLOD,50);
gd.drawString(makeNum(),0,40);//这⾥40,是makenum()数字底部到图⽚背景顶部的距离
//告诉浏览器,这个请求⽤图⽚⽅式打开
resp.setContentType("image/jpeg");
//⽹站存在缓存,不让浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
//把图⽚写给浏览器
ImageIO.write(image,"jpg",OutputStream());
}
java生成随机数的方法
//⽣成随机数,不够七位的在前⾯补0
private String makeNum(){
Random random=new Random();
String num= Int(9999)+"";//随机数范围是[0,9999)包括0,但不包括9999
StringBuffer sb=new StringBuffer();
for(int i=0;i<7-num.length();i++){
sb.append("0");
}
String()+num;
return num;
}
}
在l中注册此类;
<servlet>
<servlet-name>draw</servlet-name>
<servlet-class>com.servlet.DrawDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>draw</servlet-name>
<url-pattern>/draw</url-pattern>
</servlet-mapping>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。