1. 程式人生 > >springboot 整合kaptcha驗證碼Demo

springboot 整合kaptcha驗證碼Demo

驗證碼(CAPTCHA)是“Completely Automated Public Turing test to tell Computers and Humans Apart”(全自動區分計算機和人類的圖靈測試)的縮寫,是一種區分使用者是計算機還是人的公共全自動程式。可以防止:惡意破解密碼、刷票、論壇灌水,有效防止某個黑客對某一個特定註冊使用者用特定程式暴力破解方式進行不斷的登陸嘗試,實際上用驗證碼是現在很多網站通行的方式,我們利用比較簡易的方式實現了這個功能。今天給大家介紹一下kaptcha的和springboot一起使用的簡單例子。

準備工作

1.首要要有一個可以執行的springboot的專案並可以正常執行

2.匯入kaptcha依賴

<!--驗證碼-->
<dependency>
   <groupId>com.github.penggle</groupId>
   <artifactId>kaptcha</artifactId>
   <version>2.3.2</version>
</dependency>

開始試驗

我們有兩種方式在springboot中使用kaptcha

1.使用.xml的配置方式配置生成kaptcha的bean物件,在啟動類上@ImportResource這個xml檔案;在controller中注入其物件並使用

2.是把kaptcha作為工程的一個類,加上@component註解在返回kaptcha的方法中加上@Bean註解,再在controller中注入其物件。

第一種方法

在resources中建立一個kaptchaConfig.xml檔案 如:

kaptchaConfig.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"> <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"> <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> <!--驗證碼儲存在session的key--> <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> <!--干擾顏色,合法值: r,g,b 或者 white,black,blue.--> <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>

在springboot啟動類上引入這個檔案

@SpringBootApplication
@ImportResource(locations={"classpath:kaptchaConfig.xml"})
public class CodeDemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(CodeDemoApplication.class, args);
    }
}

在controller中注入DefaultKaptcha 

@Autowired
    DefaultKaptcha defaultKaptcha;

在controller中編寫獲取驗證碼圖片的方法

//獲取驗證碼
    @RequestMapping("/getCode")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生產驗證碼字串並儲存到session中
            String createText = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute("vrifyCode", createText);
            //使用生產的驗證碼字串返回一個BufferedImage物件並轉為byte寫入到byte陣列中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //定義response輸出型別為image/jpeg型別,使用response輸出流輸出圖片的byte陣列
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

在controller中編寫驗證的方法

//驗證碼驗證
    @RequestMapping("/checkCode")
    @ResponseBody
    public boolean imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
        String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifyCode");
        String parameter = httpServletRequest.getParameter("code");
        log.info("Session  vrifyCode ---->"+captchaId+"---- form code --->"+parameter);
        if (!captchaId.equals(parameter)) {
            log.info("錯誤的驗證碼");
            return false;
        } else {
            return true;
        }
    }

模板頁面register.html

......
<div class="form-group">
                <label class="col-md-2 col-md-offset-2 control-label">驗證碼</label>
                <div class="col-md-3">
                    <div class="row_bj" style="width:100%;">
                        <input type="text" class="form-control" id="code" name="code" required placeholder="請輸入驗證碼">
                        <img alt="驗證碼" onclick = "this.src='/getCode?d='+new Date()*1" src="/getCode" style="margin-left:20px;"/>
                    </div>
                    <label class="control-label text-danger" id="code2">(驗證碼錯誤)</label>
                </div>
            </div>
......

啟動訪問

控制檯日誌結果:

第二種方法:這種方法把.xml檔案換成使用程式碼來配置:

KaptchaConfig配置類:

@Component
public class KaptchaConfig {
    @Bean
    public DefaultKaptcha getDefaultKaptcha(){
        com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", "no");
        properties.setProperty("kaptcha.border.color", "105,179,90");
        properties.setProperty("kaptcha.textproducer.font.color", "red");
        properties.setProperty("kaptcha.image.width", "110");
        properties.setProperty("kaptcha.image.height", "40");
        properties.setProperty("kaptcha.textproducer.font.size", "40");
        properties.setProperty("kaptcha.session.key", "code");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "宋體,楷體,微軟雅黑");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

注意要去掉啟動類中引入的.xml檔案,不然會有兩個相同的物件,而你沒有指明要注入哪一個的話啟動會失敗。

補充:對於kaptcha的配置屬性可以百度找一找。