用Response做图片验证

大致步骤如下:

  • 浏览器隔3秒自动刷新一次
  • 在内存中创建一个图片
  • 得到图片
  • 设置背景图片
  • 给图片写数据
  • 让浏览器以图片的方式打开
  • 把图片写给浏览器
  • 最后,在web.xml上面配置

public class ImageResponse 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_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("expires",-1);
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma","no-cache");

        //把图片写给浏览器
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }

    private String makeNum() {
        Random random = new Random();
         String num = random.nextInt(99999999) + "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 7 -num.length(); i++) {
            sb.append("0");
        }
        num = sb.toString() + num;
        return num;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <servlet>
        <servlet-name>ImageResponse</servlet-name>
        <servlet-class>com.xiaomu.ImageResponse</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ImageResponse</servlet-name>
        <url-pattern>/img</url-pattern>
    </servlet-mapping>
</web-app>

展示!!注意要在地址栏上面加上在web.xml上面的映射地址

image

posted @ 2022-11-02 19:58  萧木XIAOMU  阅读(72)  评论(0编辑  收藏  举报