新建Servlet
package com.xinzhi.servlet;
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.nio.Buffer;
import java.util.Random;
/**
* @author lzp
* @create 2020/7/26
*/
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如何让浏览器五秒刷新一次;
resp.setHeader("refresh","60");
//在内存中创建一个图片
BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
//得到图片
Graphics2D graphics = (Graphics2D) image.getGraphics(); //笔
//设置图片的背景颜色
graphics.setColor(Color.white);
graphics.fillRect(0,0,80,20); //填充满刚刚创建的图片
//给图片写数据
Random random = new Random();// 生成随机数
graphics.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110))); //画笔颜色rgb编程随机数 也可以Color.BLUE
graphics.setFont(new Font(null,Font.BOLD,20));
graphics.drawString(makeNum(),0,20);
//绘制干扰线
graphics.setColor(Color.BLUE);
int x1;
int x2;
int y1;
int y2;
int width = 120;
int height = 30;
for (int i = 0; i < 30; i++) {
x1 = random.nextInt(width);
x2 = random.nextInt(30);
y1 = random.nextInt(height);
y2 = random.nextInt(30);
graphics.drawLine(x1, y1, x1 + x2, x2 + y2);
}
//告诉浏览器这个请求用图片的方式打开
resp.setContentType("image/jpeg");
resp.setDateHeader("expires",-1); //网站存在缓存,不让浏览器缓存
resp.setHeader("Cache-Control","no-cache"); //不缓存
resp.setHeader("Pragma","no-cache");
//把图片写给浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
}
//生成随机数
public String makeNum(){
Random random = new Random();//创建随机数
String num = random.nextInt(9999999)+"";//999999代表七位数 +""表示成为String
StringBuffer sb = new StringBuffer(); //写到流中
for (int i = 0; i < 7-num.length(); i++) {
sb.append("0"); //每次追加一个数字,保证随机数是七位,如果不是七位可以用0填充
}
num = sb.toString()+num;
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>com.xinzhi.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<!--这里可以配多个路径-->
<url-pattern>/Img</url-pattern>
<url-pattern>/img</url-pattern>
</servlet-mapping>
</web-app>