首頁 > Java > java教程 > 主體

SpringBoot如何使用Kaptcha實作驗證碼的生成與驗證功能

王林
發布: 2023-05-13 10:28:13
轉載
1635 人瀏覽過

當我們在專案中登入使用驗證碼的時候,不妨試試Kaptcha產生驗證碼,非常簡單

1、首先,我們在pom.xml檔中引入kaptcha的maven依賴

<!-- kaptcha验证码 -->
<dependency>
	<groupId>com.github.penggle</groupId>
	<artifactId>kaptcha</artifactId>
	<version>2.3.2</version>
</dependency>
登入後複製

2、然後,我們寫kaptcha的設定類別:KaptchaConfig.java

package com.lzzy.meet.common.kaptcha;
 
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.Properties;
 
/**
 * @ClassName KaptchaConfig
 * kaptcha配置类
 * @Author 
 * @Date 2019-09-05 13:50:50
 * @Version 1.0
 **/
@Slf4j
@Component
public class KaptchaConfig {
 
    @Bean
    public DefaultKaptcha getKaptcheCode() {
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", "no");
        properties.setProperty("kaptcha.textproducer.font.color", "black");
        properties.setProperty("kaptcha.image.width", "100");
        properties.setProperty("kaptcha.image.height", "36");
        properties.setProperty("kaptcha.textproducer.font.size", "30");
        properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.ShadowGimpy");
        properties.setProperty("kaptcha.session.key", "code");
        properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");
        properties.setProperty("kaptcha.background.clear.from", "232,240,254");
        properties.setProperty("kaptcha.background.clear.to", "232,240,254");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "彩云,宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}
登入後複製

3、接下來,我們寫kaptcha的控制層:KaptchaController.java

package com.lzzy.meet.common.kaptcha;
 
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
 
/**
 * @ClassName KaptchaController
 * kaptcha调用
 * @Author 
 * @Date 2019-09-05 13:59:59
 * @Version 1.0
 **/
@Slf4j
@Controller
@RequestMapping("kaptcha")
public class KaptchaController {
 
    @Autowired
    private Producer producer;
 
    @GetMapping("kaptcha-image")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        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 = producer.createText();
        log.info("******************当前验证码为:{}******************", capText);
        // 将验证码存于session中
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        BufferedImage bi = producer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        // 向页面输出验证码
        ImageIO.write(bi, "jpg", out);
        try {
        	// 清空缓存区
            out.flush();
        } finally {
        	// 关闭输出流
            out.close();
        }
    }
}
登入後複製

4、然後,我們就可以在前端呼叫katpcha的介面產生驗證碼了:

<img  th:src="@{/kaptcha/kaptcha-image}" class="ver_btn" onclick="this.src=this.src+&#39;?c=&#39;+Math.random();"/ alt="SpringBoot如何使用Kaptcha實作驗證碼的生成與驗證功能" >
登入後複製

 由於我這裡使用的是thymeleaf 模板引擎,所以路徑名稱會有點奇怪,產生的驗證碼樣式如圖:

SpringBoot如何使用Kaptcha實作驗證碼的生成與驗證功能

 5、最後,我們將使用者在用戶端登陸時輸入的驗證碼傳送到服務端進行驗證:

/**
	 * 验证验证码
	 * @param
	 * @return 正确:true/错误:false
	 */
	public static boolean validate(String registerCode) {
		// 获取Session中验证码
		Object captcha = ServletUtils.getAttribute(Constants.KAPTCHA_SESSION_KEY);
		// 判断验证码是否为空
		if (StringUtils.isEmpty(registerCode)) {
			return false;
		}
		// 校验验证码的正确与否
		boolean result = registerCode.equalsIgnoreCase(captcha.toString());
		if (result) {
			// 正确了后,将验证码从session中删掉
			ServletUtils.getRequest().getSession().removeAttribute(Constants.KAPTCHA_SESSION_KEY);
		}
		// 返回验证结果
		return result;
	}
登入後複製

以上是SpringBoot如何使用Kaptcha實作驗證碼的生成與驗證功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:yisu.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!