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.util.Random;
/**
* Servlet 生成一个简易的图片验证码,并3秒刷新一次
* */
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 让浏览器页面3秒自动刷新
resp.setHeader("refresh","3");
// 在内存创建一个图片
BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_BGR);
// 得到图片
Graphics2D graphics2D = (Graphics2D)image.getGraphics(); // 相当于画笔
// 设置图片的背景颜色
graphics2D.setColor(Color.white);
graphics2D.fillRect(0,0,80,20);
// 给图片写数据
graphics2D.setColor(Color.BLUE);
graphics2D.setFont(new Font(null,Font.BOLD,20));
graphics2D.drawString(getRandomNum(),0,20);
// 告诉浏览器以图片的方式打开
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());
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
// 生成随机数
public String getRandomNum(){
Random random = new Random();
String num = random.nextInt(9999999) + "";
StringBuilder stringBuffer = new StringBuilder();
for (int i=0;i<7-num.length();i++){
stringBuffer.append(0);
}
num = stringBuffer.toString()+num;
return num;
}
}
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>
<servlet-name>img</servlet-name>
<servlet-class>com.test.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>img</servlet-name>
<url-pattern>/img</url-pattern>
</servlet-mapping>
</web-app>
生成效果(每三秒书刷新一次):
?
|