您好,欢迎来到华佗健康网。
搜索
您的当前位置:首页springboot生成图片验证码,使用开源kaptcha

springboot生成图片验证码,使用开源kaptcha

来源:华佗健康网

springboot生成图片验证码,使用开源kaptcha,三步搞定

一、Pom导入依赖
        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>
二、自定义图片验证码相关配置
@Configuration
public class CaptchaConfig {

    @Bean
    public Producer captcha() {
        // 配置图形验证码的基本参数
        Properties properties = new Properties();
        //图片长度
        properties.setProperty("kaptcha.image.width", "150");
        //图片高度
        properties.setProperty("kaptcha.image.height", "50");
        //生成的验证码使用到的内容
        properties.setProperty("kaptcha.textproducer.char.string", "01234567");
        //生成验证码长度
        properties.setProperty("kaptcha.textproducer.char.length", "2");
        //验证码颜色
        properties.setProperty("kaptcha.textproducer.font.color", "red");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}
三、编写接口生成图片验证码
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private Producer captchaProducer;

    @GetMapping("/captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");
            // 创建验证码文本
            String capText = captchaProducer.createText();
            // 将验证码文本设置到session,名字为captcha,取的时候通过captcha取
            request.getSession().setAttribute("captcha", capText);
            BufferedImage image = captchaProducer.createImage(capText);
            ServletOutputStream out = response.getOutputStream();
            ImageIO.write(image, "jpg", out);
            try {
                out.flush();
            } finally {
                out.close();
            }
        } catch (IOException e) {
            log.info("登录:获取图片验证码异常!");
        }
    }
}

四、测试接口

五、验证码比对
   public boolean isSuccessCaptcha(HttpServletRequest request) {
		//从session获取当前图片验证码的值
        String captcha = request.getParameter("captcha");
        //获取用户传入的验证码值
        Object sessionCaptcha = request.getSession().getAttribute("userCaptcha");
        if (sessionCaptcha == null) {
            return false;
        }
        return sessionCaptcha.toString().equals(captcha);
    }

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo0.com 版权所有 湘ICP备2023021991号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务