Java implements random letter verification code

Today I will bring you ideas for random letter verification codes and code sharing.

Before doing this, we must first think about the code idea of ​​this function.

        Let’s start from the front desk

        When the front desk needs to generate a verification code, it requests data from the background, and then the background receives the request and starts generating the verification code. The specific method is to use java graphics drawing and random numbers to filter letters.

        Draw the generated verification code on the picture, and then return the picture and the generated letters to the front desk. The front desk receives the picture and displays it, and compares the received letters with the user's letters to see if they are correct.

The analysis ends here, let’s go directly to the code!

The first is the java class generated by the verification code

Write a servlet class

 

resp.setContentType("image/jpeg") is to set the file type. Because what we want to return is a picture, we set it to the picture format.

Then define the width and height attributes required by our image

 Use the BufferedImage class to obtain an artboard with attributes (width, height, color format)

Then use the artboard to get the Graphics brush

Create a new font with the attributes (font type, font bold, font size)

Set font to brush

 We need to give the picture a background

Get the path to the image, then use ImageIO to read the image in, and then import the image we want to generate.

 new a Random random number

Then create the random string we want

Define an empty string variable to facilitate splicing strings later

Define another character variable to store random letters

 

 Use for loop as many times as you want for the verification code.

I only need 5 digits in length here and only looped 5 times.

Define the tempIndex variable to receive a random number (randomly pick a subscript from the string)

Then use this subscript tempIndex to intercept characters using charAr in the string template, and you will get the random character tempNum.

Then splice the random character tempNum into the string s

new color, set a random color, the type is (r, g, b)

Give color to brush

Then write the random characters tempNum on the drawing board. The x-axis is 18*i+5. This is to prevent the verification characters from overlapping. Each new verification code must be distanced from the previous one.

 

 Finally, let’s put the spliced ​​string s into the session so that the front desk can know what our verification code is before we can verify it.

Then create the stream ots and use ImageIO's write to write our pictures to the front desk.

At this point, the backend is finished.

 

 At the front desk, you only need to write the path as our servlet class to get the image.

 The renderings are as follows:

 

The code has been written so far. You can follow my ideas and try it yourself.

If you really don’t understand, I will publish the source code here.

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
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.File;
import java.io.IOException;
import java.util.Random;

@WebServlet("/CaptchaDemo")
public class CaptchaDemo extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //文件类型
        resp.setContentType("image/jpeg");
        //设置缓存
        resp.setHeader("Pragma","no-cache");
        resp.setHeader("Cache-Control","no-cache");
        resp.setDateHeader("Expires",0);

        int width = 100;
        int height = 40;

        //画板
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //画笔
        Graphics g = image.getGraphics();
        //字体
        Font font = new Font("微软雅黑",Font.BOLD,25);
        //设置字体
        g.setFont(font);

        //获得图片路径
        String imagePath = req.getServletContext().getRealPath("/img/main-banner.jpg");
        Image image1 = ImageIO.read(new File(imagePath));

        //引入背景图片
        g.drawImage(image1,0,0,100,40,null);

        //随机数
        Random random = new Random();
        //要随机的字符串
        String template = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String s = "";
        char tempNum;
        for (int i = 0; i < 5; i++){
            //获取随机出的字符
            int tempIndex = random.nextInt(template.length()-1);
            tempNum = template.charAt(tempIndex);
            //拼成字符串
            s+=tempNum;
            //设置颜色
            Color color = new Color(20+random.nextInt(110),20+random.nextInt(110),random.nextInt(110));
            g.setColor(color);
            //字母写入图片
            g.drawString(String.valueOf(tempNum),18*i+5,25);
        }
        req.getSession().setAttribute("s",s);
        //获取流发送给前台
        ServletOutputStream ots = resp.getOutputStream();
        ImageIO.write(image,"JPEG",ots);
    }
}

Next time I will teach you how to write other verification codes!

Guess you like

Origin blog.csdn.net/hy123154/article/details/128140566