美文网首页
springboot中引入图片验证码

springboot中引入图片验证码

作者: 贝影grass | 来源:发表于2019-11-12 20:54 被阅读0次

在进行web开发中,我们时常要进行登录验证,其中最常见的便是图片验证,本文将介绍如何在springboot中引入图片验证码

我们使用的是Kaptcha图片验证码生成器,最终效果如下图

image.png

1.先在pom中引入Kaptcha jar包

image.png

2.在application.properties中配置Kaptcha的样式,即设置图片验证码的属性,如边框,使用的字符,字符颜色等属性

image.png

3.在java包新建config包,在包下新建Kaptcah的配置类

   我的工程目录如下
image.png

配置类内容如下

@Configuration //加入配置注解,springboot会自动扫描,作为配置文件
public class KaptchaConfig {
    @Value("${kaptcha.border}")
    private String border;

    @Value("${kaptcha.textproducer.font.color}")
    private String fcolor;

    @Value("${kaptcha.image.width}")
    private String width;

    @Value("${kaptcha.textproducer.char.string}")
    private String cString;

    @Value("${kaptcha.image.height}")
    private String height;

    @Value("${kaptcha.textproducer.font.size}")
    private String fsize;

    @Value("${kaptcha.noise.color}")
    private String nColor;

    @Value("${kaptcha.textproducer.char.length}")
    private String clength;

    @Value("${kaptcha.textproducer.font.names}")
    private String fnames;

    /**
     * 由于web.xml不生效了,需要在这里配置Kaptcha验证码Servlet
     */
    @Bean //表明配置bean
    public ServletRegistrationBean<KaptchaServlet> servletRegistrationBean() throws ServletException {
        ServletRegistrationBean<KaptchaServlet> servlet = new ServletRegistrationBean<KaptchaServlet>(new KaptchaServlet(), "/Kaptcha");
        servlet.addInitParameter("kaptcha.border", border);// 无边框
        servlet.addInitParameter("kaptcha.textproducer.font.color", fcolor); // 字体颜色
        servlet.addInitParameter("kaptcha.image.width", width);// 图片宽度
        servlet.addInitParameter("kaptcha.textproducer.char.string", cString);// 使用哪些字符生成验证码
        servlet.addInitParameter("kaptcha.image.height", height);// 图片高度
        servlet.addInitParameter("kaptcha.textproducer.font.size", fsize);// 字体大小
        servlet.addInitParameter("kaptcha.noise.color", nColor);// 干扰线的颜色
        servlet.addInitParameter("kaptcha.textproducer.char.length", clength);// 字符个数
        servlet.addInitParameter("kaptcha.textproducer.font.names", fnames);// 字体
        return servlet;
    }
}

其中的 ServletRegistrationBean<KaptchaServlet> servlet = new ServletRegistrationBean<KaptchaServlet>(new KaptchaServlet(), "/Kaptcha")表示

在前端中使用“/Kaptcha"即可引用Kaptcha图片验证

通过以上几步,即可在springboot中引入Kaptcha,进行图片验证。

相关文章

网友评论

      本文标题:springboot中引入图片验证码

      本文链接:https://www.haomeiwen.com/subject/vitcictx.html