JavaWeb case (two): use the response object to realize the verification code

I. Introduction

Before developing this feature, we must first think about a question, where did the verification code come from? It can be divided into two implementation methods.

  1. Front-end implementation (js)
  2. For back-end implementation, you need to use the java picture class to generate a picture (the back-end implementation is used today)

Two, code demonstration

package com.xu.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;

public class ImageServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //如何让浏览器3s刷新一次
        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/jpg");
        //网站存在缓存,不让浏览器环存
        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(9999999) + "";//代表7位数的验证码
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 7 - num.length(); i++) {
    
    
            sb.append("0");
        }
        String s = sb.toString() + num;
        return num;
    }

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

After writing the code, configure the web.xml access address, and then access the code to get the verification code, and refresh it every 3 seconds, the effect is as follows:
Insert picture description here

3. Summary:

In fact , you can understand the above code . Now no one uses this kind of code to realize the verification code function. We only need to learn its principles and ideas . The GUI technology is a bit outdated .

Guess you like

Origin blog.csdn.net/weixin_46594796/article/details/109399124
Recommended