Spring Boot2.7 generates image verification code for login

First inject dependencies in pom.xml

<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

Then we need to declare the DefaultKaptcha bean object in the configuration file.
Insert image description here
Then we can find a directory and create a class called CaptchaGenerator.java
to specifically handle the logic of generating verification codes.

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;

@Component
public class CaptchaGenerator {
    
    

    private DefaultKaptcha defaultKaptcha;

    @Autowired
    public CaptchaGenerator(DefaultKaptcha defaultKaptcha) {
    
    
        this.defaultKaptcha = defaultKaptcha;
    }

    public byte[] generateCaptchaImage(String captchaText) throws IOException {
    
    
        Properties properties = new Properties();
        properties.setProperty("kaptcha.textproducer.char.string", "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
        properties.setProperty("kaptcha.textproducer.char.length", "4");

        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);

        BufferedImage captchaImage = defaultKaptcha.createImage(captchaText);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(captchaImage, "jpg", outputStream);

        return outputStream.toByteArray();
    }
}

Then declare the CaptchaGenerator object in the class that writes the interface.
Note that you must use the constructor method to assign values
, otherwise you will not be able to get things.
Insert image description here

private CaptchaGenerator captchaGenerator;

@Autowired
public BookController(CaptchaGenerator captchaGenerator) {
    
    
    this.captchaGenerator = captchaGenerator;
}

Finally write the function

@GetMapping(value = "/captcha", produces = MediaType.IMAGE_JPEG_VALUE)
public void getCaptchaImage(HttpServletResponse response) throws IOException {
    
    
    String captchaText = "3922";// 生成验证码文本
    byte[] captchaImage = captchaGenerator.generateCaptchaImage(captchaText);

    response.setContentType(MediaType.IMAGE_JPEG_VALUE);
    response.getOutputStream().write(captchaImage);
    response.getOutputStream().flush();
}

Insert image description here

Then we directly access the port + interface prefix/captcha to access the verification code. The verification
Insert image description here
code content I set here is 3922. You can modify it according to the situation. It is usually random.

Guess you like

Origin blog.csdn.net/weixin_45966674/article/details/133019839