MENU

springboot配置验证码功能笔记

March 16, 2021 • 开发

①pom.xml安装依赖

<dependency>
       <groupId>com.github.axet</groupId>
       <artifactId>kaptcha</artifactId>
       <version>0.0.9</version>
</dependency>

②创建一个KaptchaConfig.java

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * @author: xupt
 * @Date: 2021/3/16 上午10:08
 * @Description:验证码配置类
 */
@Configuration
public class KaptchaConfig {
    @Bean
    public DefaultKaptcha producer() {
        Properties properties = new Properties();
        // 图片边框
        properties.setProperty("kaptcha.border", "no");
        // 字体颜色
        properties.setProperty("kaptcha.textproducer.font.color", "red");
        // 字体大小
        properties.setProperty("kaptcha.textproducer.font.size", "30");
        // session key
        properties.setProperty("kaptcha.session.key", "code");
        // 验证码长度
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        // 字体
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

③获取验证码

@GetMapping("kaptcha")
public void getKaptcha(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*/
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        /*设置过期时间*/
        session.setMaxInactiveInterval(60);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
}

④验证验证码

@PostMapping("login")
public ResultVO login(@RequestBody RequestLoginVO requestLoginVO, HttpServletRequest request) {
        HttpSession session = request.getSession();
        /*出去session中存取的验证码内容*/
        String sessionKaptCha = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        /*进行验证*/
        if (!sessionKaptCha.equals(requestLoginVO.getKaptcha())) {
            return new ResultVO(ResCode.ERROR, Consts.KAPTCHA_ERROR);
        }
        return new ResultVO(ResCode.SUCCESS);
}
转载请注明出处,并添加原文地址

Archives QR Code Tip
QR Code for this page
Tipping QR Code