springboot整合kaptcha验证码

简介: 前言:关于kaptcha简介以及spring整合kaptcha以及在Linux上验证码显示乱码问题,我在另一篇文章中已详细讲解,请参考:spring整合kaptcha验证码。

前言:

关于kaptcha简介以及spring整合kaptcha以及在Linux上验证码显示乱码问题,我在另一篇文章中已详细讲解,请参考:spring整合kaptcha验证码
本文将介绍springboot整合kaptcha的两种方式。点 下载源码。

开发工具及技术:

1、idea 2017
2、springboot 2.0.2
3、kaptcha

正式开始:

方式一:通过kaptcha.xml配置

1、用idea新建一个spring Initializr
2、添加kaptcha的依赖:

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

3、在resources下面新建kaptcha.xml,内容如下:
kaptcha.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 生成kaptcha的bean-->
    <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
        <property name="config">
            <bean class="com.google.code.kaptcha.util.Config">
                <constructor-arg type="java.util.Properties">
                    <!--设置kaptcha属性 -->
                    <props>
                        <prop key = "kaptcha.border ">yes</prop>
                        <prop key="kaptcha.border.color">105,179,90</prop>
                        <prop key="kaptcha.textproducer.font.color">blue</prop>
                        <prop key="kaptcha.image.width">100</prop>
                        <prop key="kaptcha.image.height">50</prop>
                        <prop key="kaptcha.textproducer.font.size">27</prop>
                        <prop key="kaptcha.session.key">code</prop>
                        <prop key="kaptcha.textproducer.char.length">4</prop>
                        <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>
                        <prop key="kaptcha.textproducer.char.string">0123456789ABCEFGHIJKLMNOPQRSTUVWXYZ</prop>
                        <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.WaterRipple</prop>
                        <prop key="kaptcha.noise.color">black</prop>
                        <prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.DefaultNoise</prop>
                        <prop key="kaptcha.background.clear.from">185,56,213</prop>
                        <prop key="kaptcha.background.clear.to">white</prop>
                        <prop key="kaptcha.textproducer.char.space">3</prop>
                    </props>
                </constructor-arg>
            </bean>
        </property>
    </bean>
</beans>

注:kaptcha.xml中的内容其实就是和spring 整合kaptcha时spring-kaptcha.xml中内容一样,就是将kaptcha交给spring容器管理,设置一些属性,然后要用的时候直接注入即可。

4、加载kaptcha.xml:
在springboot启动类上加上@ImportResource(locations = {"classpath:kaptcha/kaptcha.xml"}),加了这个注解,springboot就会去加载kaptcha.xml文件。注意kaptcha.xml的路径不要写错,classpath在此处是resources目录。

5、编写controller用于生成验证码:
CodeController.java

@Controller
public class CodeController {
    @Autowired
    private Producer captchaProducer = null;
    @RequestMapping("/kaptcha")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //生成验证码
        String capText = captchaProducer.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        //向客户端写出
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}

注:在这个controller径注入刚刚kaptcha.xml中配置的那个bean,然后就可以使用它生成验证码,以及向客户端输出验证码;记住这个类的路由,前端页面验证码的src需要指向这个路由。

6、新建验证码比对工具类:
CodeUtil.java

public class CodeUtil {
    /**
     * 将获取到的前端参数转为string类型
     * @param request
     * @param key
     * @return
     */
    public static String getString(HttpServletRequest request, String key) {
        try {
            String result = request.getParameter(key);
            if(result != null) {
                result = result.trim();
            }
            if("".equals(result)) {
                result = null;
            }
            return result;
        }catch(Exception e) {
            return null;
        }
    }
    /**
     * 验证码校验
     * @param request
     * @return
     */
    public static boolean checkVerifyCode(HttpServletRequest request) {
        //获取生成的验证码
        String verifyCodeExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        //获取用户输入的验证码
        String verifyCodeActual = CodeUtil.getString(request, "verifyCodeActual");
        if(verifyCodeActual == null ||!verifyCodeActual.equals(verifyCodeExpected)) {
            return false;
        }
        return true;
    }
}

注:这个类用来比对生成的验证码与用户输入的验证码。生成的验证码会自动加到session中,用户输入的通过getParameter获得。注意getParameterkey值要与页面中验证码的name值一致。

7、使用验证码:
①Controller
HelloWorld.java

@RestController
public class HelloWorld {
    @RequestMapping("/hello")
    public String hello(HttpServletRequest request) {
        if (!CodeUtil.checkVerifyCode(request)) {
            return "验证码有误!";
        } else {
            return "hello,world";
        }
    }
}

②页面
hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function refresh() {
            document.getElementById('captcha_img').src="/kaptcha?"+Math.random();
        }
    </script>
</head>
<body>
<form action="/hello" method="post">
    验证码:  <input type="text" placeholder="请输入验证码" name="verifyCodeActual">
    <div class="item-input">
        <img id="captcha_img" alt="点击更换" title="点击更换"
             onclick="refresh()" src="/kaptcha" />
    </div>
    <input type="submit" value="提交" />
</form>

</body>
</html>

注意:验证码本质是一张图片,所以用<img >标签,然后通过src = "/kaptcha"指向生成验证码的那个controller的路由即可;通过onclick = “refresh()”调用js代码实现点击切换功能;<input name = "verifyCodeActual ">中要注意name的值,在CodeUtil中通过request的getParameter()方法获取用户输入的验证码时传入的key值就应该和这里的name值一致。

8、测试:
输入正确的验证码

img_081c13c063a1ab4962fc8a2bb41ef5f0.png
图片发自简书App

验证通过


img_fc3e6e44f6e60f5285367acb35f930b5.png
图片发自简书App

输入错误的验证码


img_9f300b9f0353843e633d3a041181f71f.png
图片发自简书App

验证未通过


img_53a60f1fd3e98db2c4f82d2b78225856.png
图片发自简书App

方式二:通过配置类来配置kaptcha

1、配置kaptcha
相比于方式一,一增二减。
减:
把kaptcha.xml删掉
把启动类上的@ImportResource(locations = {"classpath:kaptcha/kaptcha.xml"})注解删掉

增:
新建KaptchaConfig配置类,内容如下:
KaptchaConfig.java

@Configuration
public class KaptchaConfig {
    @Bean
    public DefaultKaptcha getDefaultKaptcha(){
        DefaultKaptcha captchaProducer = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", "yes");
        properties.setProperty("kaptcha.border.color", "105,179,90");
        properties.setProperty("kaptcha.textproducer.font.color", "blue");
        properties.setProperty("kaptcha.image.width", "110");
        properties.setProperty("kaptcha.image.height", "40");
        properties.setProperty("kaptcha.textproducer.font.size", "30");
        properties.setProperty("kaptcha.session.key", "code");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        captchaProducer.setConfig(config);
        return captchaProducer;

    }
}

注:这个类用来配置Kaptcha,就相当于方式一的kaptcha.xml,把kaptcha加入IOC容器,然后return 回一个设置好属性的实例,最后注入到CodeController中,在CodeController中就可以使用它生成验证码。要特别注意return captchaProducer;private Producer captchaProducer = null;captchaProducer名字要一样,不然就加载不到这个bean。

2、测试:
输入正确的验证码:

img_a02158933c83d7af0c2b667c4cb571b2.png
图片发自简书App

验证通过


img_6e8c8fa418de457222116376948541cd.png
图片发自简书App

输入错误的验证码


img_b89fbf81e1f9d1e76c73d90f1ed79d8a.png
图片发自简书App

验证未通过


img_1333c2f175bf04f19ce360f3c5dec7a0.png
图片发自简书App

为了说明两次的验证码是基于两种方式生成的,方式一和方式二的验证码我设置了不同的属性,从图片中可以看出两次验证码的颜色、干扰线、背景等都有不同。

总结:

1、过程梳理:
不论是哪种方式,都是把kaptcha加入spring容器,即要有一个kaptcha的bean;新建一个controller,把kaptcha的bean注入到controller中用于生成验证码;然后需要有一个比对验证码的工具类,在测试的controller中调用工具类进行验证码比对;最后在前端页面只需要用一个<img src = "/生成验证码的controller的路由">即可获取验证码,通过给这个img标签加点击事件就可实现“点击切换验证码”。

2、与spring整合kaptcha对比
spring整合kaptcha也介绍了两种方式,在web.xml中配置最简洁,不需要写生成验证码的controller,在页面中直接用src指向web.xml中kaptcha的servlet 的<url-pattern >的值即可。
springboot整合kaptcha的两种方式都类似于spring整合kaptcha的第二种方式,都是先配置bean,然后用controller生成验证码,前端用src指向这个controller,不同之处在于:假如生成验证码的controller路由为/xxx,那么spring 整合kaptcha时src = “xxx.jpg”,springboot整合kaptcha时src = "/xxx"

以上内容属于个人笔记整理,如有错误,欢迎批评指正!

相关文章
|
2月前
|
前端开发 安全 Java
SpringBoot 实现登录验证码(附集成SpringSecurity)
SpringBoot 实现登录验证码(附集成SpringSecurity)
|
8月前
|
前端开发 安全 Java
SpringBoot最简单的登陆验证码+6套主页-【JSB项目实战】
SpringBoot最简单的登陆验证码+6套主页-【JSB项目实战】 CSDN 转过来的,所以格式与内容有些许错误请见谅
SpringBoot最简单的登陆验证码+6套主页-【JSB项目实战】
|
1月前
|
前端开发 JavaScript Java
springboot 集成easy-captcha实现图像验证码显示和登录
springboot 集成easy-captcha实现图像验证码显示和登录
135 0
|
1月前
|
前端开发 NoSQL Java
【SpringBoot】秒杀业务:redis+拦截器+自定义注解+验证码简单实现限流
【SpringBoot】秒杀业务:redis+拦截器+自定义注解+验证码简单实现限流
|
8月前
|
Java
|
12天前
|
人工智能 前端开发 安全
springboot项目使用谷歌的kaptcha生成验证码超级简单
springboot项目使用谷歌的kaptcha生成验证码超级简单
63 0
|
5月前
|
存储 前端开发 Java
SpringBoot实现简单的登录验证码
SpringBoot实现简单的登录验证码
180 0
|
5月前
|
存储 前端开发 Java
SpringBoot实现简单的登录验证码
SpringBoot实现简单的登录验证码
80 0
|
8月前
|
缓存 前端开发 NoSQL
前后端分离,SpringBoot如何实现验证码操作
前后端分离,SpringBoot如何实现验证码操作
124 0
|
10天前
|
Java Linux
Springboot 解决linux服务器下获取不到项目Resources下资源
Springboot 解决linux服务器下获取不到项目Resources下资源