Home >Java >javaTutorial >How SpringBoot uses Kaptcha to implement verification code generation and verification functions

How SpringBoot uses Kaptcha to implement verification code generation and verification functions

王林
王林forward
2023-05-13 10:28:131751browse

When we log in and use the verification code in the project, we might as well try Kaptcha to generate the verification code. It is very simple.

1. First, we introduce kaptcha in the pom.xml file maven dependency

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

2. Then, we write kaptcha’s configuration class: KaptchaConfig.java

package com.lzzy.meet.common.kaptcha;
 
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.Properties;
 
/**
 * @ClassName KaptchaConfig
 * kaptcha配置类
 * @Author 
 * @Date 2019-09-05 13:50:50
 * @Version 1.0
 **/
@Slf4j
@Component
public class KaptchaConfig {
 
    @Bean
    public DefaultKaptcha getKaptcheCode() {
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", "no");
        properties.setProperty("kaptcha.textproducer.font.color", "black");
        properties.setProperty("kaptcha.image.width", "100");
        properties.setProperty("kaptcha.image.height", "36");
        properties.setProperty("kaptcha.textproducer.font.size", "30");
        properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.ShadowGimpy");
        properties.setProperty("kaptcha.session.key", "code");
        properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");
        properties.setProperty("kaptcha.background.clear.from", "232,240,254");
        properties.setProperty("kaptcha.background.clear.to", "232,240,254");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "彩云,宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

3. Next, we write kaptcha’s control layer: KaptchaController.java

package com.lzzy.meet.common.kaptcha;
 
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
 
/**
 * @ClassName KaptchaController
 * kaptcha调用
 * @Author 
 * @Date 2019-09-05 13:59:59
 * @Version 1.0
 **/
@Slf4j
@Controller
@RequestMapping("kaptcha")
public class KaptchaController {
 
    @Autowired
    private Producer producer;
 
    @GetMapping("kaptcha-image")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String capText = producer.createText();
        log.info("******************当前验证码为:{}******************", capText);
        // 将验证码存于session中
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        BufferedImage bi = producer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        // 向页面输出验证码
        ImageIO.write(bi, "jpg", out);
        try {
        	// 清空缓存区
            out.flush();
        } finally {
        	// 关闭输出流
            out.close();
        }
    }
}

4. Then, we can call the katpcha interface on the front end to generate the verification code:

<img  th:src="@{/kaptcha/kaptcha-image}" class="ver_btn" onclick="this.src=this.src+&#39;?c=&#39;+Math.random();"/ alt="How SpringBoot uses Kaptcha to implement verification code generation and verification functions" >

Since I am using the thymeleaf template engine here, the path name will be a bit strange, and the generated verification code style As shown in the figure:

How SpringBoot uses Kaptcha to implement verification code generation and verification functions

5. Finally, we send the verification code entered by the user when logging in on the client to the server for verification:

/**
	 * 验证验证码
	 * @param
	 * @return 正确:true/错误:false
	 */
	public static boolean validate(String registerCode) {
		// 获取Session中验证码
		Object captcha = ServletUtils.getAttribute(Constants.KAPTCHA_SESSION_KEY);
		// 判断验证码是否为空
		if (StringUtils.isEmpty(registerCode)) {
			return false;
		}
		// 校验验证码的正确与否
		boolean result = registerCode.equalsIgnoreCase(captcha.toString());
		if (result) {
			// 正确了后,将验证码从session中删掉
			ServletUtils.getRequest().getSession().removeAttribute(Constants.KAPTCHA_SESSION_KEY);
		}
		// 返回验证结果
		return result;
	}

The above is the detailed content of How SpringBoot uses Kaptcha to implement verification code generation and verification functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete