Functional Development of JAVA Verification Code

1. Increase the frame package of the verification code.

Add the verification code frame package to the pom.xml file

        <!-- 验证码 -->
        <dependency>
            <groupId>com.github.axet</groupId>
            <artifactId>kaptcha</artifactId>
            <version>0.0.9</version>
        </dependency>

Then download the frame package of the verification code through Maven.

2. Configure the content of the verification code.

figure 1

 

@Configuration
public class KaptchaConfig {

    @Bean
    public DefaultKaptcha producer() {
        Properties properties = new Properties();
        properties.put("kaptcha.border", "no");
        properties.put("kaptcha.textproducer.font.color", "black");
        properties.put("kaptcha.textproducer.char.space", "5");
        properties.put("kaptcha.textproducer.font.names", "Arial,Courier,cmr10,宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }

}

3. Verification code interface method.

figure 2

 

3.1. Reference verification code:

import com.google.code.kaptcha.Producer;

3.2. Annotate the referenced verification code method and inject the required external resources, which is the content resource of the verification code configured above:

@Autowired
private Producer producer;

3.3. By GET request:

@GetMapping("captcha.jpg")

3.4. Verification code method:

    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到session
        HttpSession session = request.getSession();
        session.setAttribute("captcha", text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

First generate a text verification code, then generate a picture verification code, then save the text verification code in the session, and return the generated picture to the front end;

4. The front end calls the verification code interface, and displays the picture returned by the interface on the page.

code show as below:

<img src="/api/user/captcha.jpg" />


Pay attention to the official account (Moon Shadow WEB) to learn more front-end and back-end knowledge;
everyone is welcome to pay attention to mutual exchange and learning;

Guess you like

Origin blog.csdn.net/qq_34297287/article/details/125288366