SpringBoot和SSM集成验证码kaptcha(前后端代码示例+配置示例)

满足你,先看效果(样式是可以自己定制的)
在这里插入图片描述
前端代码示例

html

<!-- 验证码 -->
<img class="loginCode" src="/login/kaptcha" />

JavaScript(点击时刷新验证码)

(function (window,document) {
    //给路径加一个参数,让浏览器误以为路径变了,会重新请求
    $('.loginCode').click(function () {
        this.src = "/login/kaptcha?d="+ new Date();
    })
})(window,document)

后端代码配置和代码示例

有Maven的同学,可以在pom.xml配置(没有也没关系,下面给你准备好了jar导入即可)

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

关注微信公众号“一颗剽悍的种子”,输入“编程资源”获取jar包
在这里插入图片描述
Config 代码配置验证码属性

    @Bean
    public Producer getKaptcha(){
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        Config config = new Config(properties);
        //设置图片边框
        properties.setProperty("kaptcha.border", "yes");
        //设置边框颜色只支持RGB和英文单词颜色
        properties.setProperty("kaptcha.border.color", "75,139,244");
        //设置字体颜色只支持RGB和英文单词颜色
        properties.setProperty("kaptcha.textproducer.font.color", "75,139,244");
        //设置图片宽
        properties.setProperty("kaptcha.image.width","100");
        //设置图片高
        properties.setProperty("kaptcha.image.height","40");
        //设置字体大小
        properties.setProperty("kaptcha.image.font.size","20");
        //设置验证码长度
        properties.setProperty("kaptcha.textproducer.char.length","4");
        //设置取消干扰
        properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");
        kaptcha.setConfig(config);
        return kaptcha;
    }
}

Controller 请求时输出验证码

    @RequestMapping(path = "kaptcha", method = RequestMethod.GET)
    public void getKaptcha(HttpServletResponse response, HttpSession session) {
        String text = kaptcha.createText();
        BufferedImage image = kaptcha.createImage(text);
        /**
         * 验证码属于敏感信息,所以存在session中
         */
        session.setAttribute("kaptcha", text);
        //图片输出给浏览器
        response.setContentType("image/png");
        try {
            OutputStream out = response.getOutputStream();
            ImageIO.write(image, "png", out);
        } catch (IOException e) {
            logger.error("验证码失败:" + e.getMessage());
        }
    }

我是一颗剽悍的种子,一颗偏爱前端的后端新司机。 把我会的认真的分享——一直是我写博客的信条,把文章的代码带走,你的四连留下,点赞、收藏、评论、关注是我写博客的最大动力

猜你喜欢

转载自blog.csdn.net/A_hxy/article/details/106702475