栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

DefaultKaptcha生成验证码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

DefaultKaptcha生成验证码

第一步:导包(maven环境下)

        
            com.github.penggle
            kaptcha
            2.3.2
                
第二步:使用DefaultKaptcha类需先对验证码样式进行配置
@Configuration
public class KaptchaConfiguration {

    @Bean
    public DefaultKaptcha getDefaultKaptcha() {
        com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();
        Properties properties = new Properties();
//--------------------------------------------------------------------------------------
        properties.put("kaptcha.textproducer.char.string", "0123456789");
        properties.put("kaptcha.border", "no");
        properties.put("kaptcha.textproducer.font.color", "black");
        properties.put("kaptcha.textproducer.char.length","4");
        properties.put("kaptcha.image.height","40");
        properties.put("kaptcha.image.width","150");
        properties.put("kaptcha.textproducer.font.size","30");
        properties.put("kaptcha.session.key", "verifyCode");
        properties.put("kaptcha.textproducer.char.space", "5");
        properties.setProperty("kaptcha.image.width", "164");
        properties.setProperty("kaptcha.image.height", "64");
        properties.put("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");
//--------------------------------------------------------------------------------------
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);

        return defaultKaptcha;
    }
}

注释内的部分为验证码相关配置,可不设置,默认即可

但是Properties 和 Config 需new ,否则运行报空指针

第三步:生成验证码

@RestController
@RequestMapping("/a")
public class Kaptcha {
    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @RequestMapping("/verifyCode")
    public void defaultKaptcha (HttpServletRequest request , HttpServletResponse response) throws IOException {
        //生成验证码
        String verifyCode = defaultKaptcha.createText();
        System.out.println(verifyCode);
        //写到session中,后续和前端传来的验证码比对
        HttpSession session = request.getSession();
        session.setAttribute("verifyCode",verifyCode);
        //生成验证码图片流
        BufferedImage image = defaultKaptcha.createImage(verifyCode);
        //设置响应头
        response.setHeader("Cache-Control" , "no-store");
        response.setHeader("Pragme" , "no-cache");
        response.setDateHeader("Expires",0);
        response.setContentType("image/jpeg");
        //写到响应输出流中
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"jpg",outputStream);
        outputStream.flush();
        outputStream.close();
    }
}

Properties属性(官网或者百度即可)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/891224.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号