天天看點

springboot整合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獲得。注意getParameter的key值要與頁面中驗證碼的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、測試:

輸入正确的驗證碼

springboot整合kaptcha驗證碼前言:開發工具及技術:正式開始:總結:

圖檔發自簡書App

驗證通過

springboot整合kaptcha驗證碼前言:開發工具及技術:正式開始:總結:

輸入錯誤的驗證碼

springboot整合kaptcha驗證碼前言:開發工具及技術:正式開始:總結:

驗證未通過

springboot整合kaptcha驗證碼前言:開發工具及技術:正式開始:總結:

方式二:通過配置類來配置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、測試:

輸入正确的驗證碼:

springboot整合kaptcha驗證碼前言:開發工具及技術:正式開始:總結:
springboot整合kaptcha驗證碼前言:開發工具及技術:正式開始:總結:
springboot整合kaptcha驗證碼前言:開發工具及技術:正式開始:總結:
springboot整合kaptcha驗證碼前言:開發工具及技術:正式開始:總結:

為了說明兩次的驗證碼是基于兩種方式生成的,方式一和方式二的驗證碼我設定了不同的屬性,從圖檔中可以看出兩次驗證碼的顔色、幹擾線、背景等都有不同。

總結:

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"

以上内容屬于個人筆記整理,如有錯誤,歡迎批評指正!