生成驗(yàn)證碼
我們在登錄或注冊某個(gè)網(wǎng)站的時(shí)候,會需要我們輸入驗(yàn)證碼,才能登錄注冊,那么如何生成驗(yàn)證碼呢?其實(shí),生成驗(yàn)證碼我們可以用Java Swing在后臺內(nèi)存里的區(qū)域畫一個(gè)出來,但是非常麻煩,所以我們選擇一些現(xiàn)成的工具——Kaptcha,接下來就看看如何使用這個(gè)工具在內(nèi)存中畫出一個(gè)驗(yàn)證碼(圖片),怎么把他發(fā)送給瀏覽器,瀏覽器怎么顯示在登陸頁面的位置。
kaptcha
kaptcha 是Google開源的非常實(shí)用的自動生成驗(yàn)證碼的一個(gè)工具,有了它,你可以生成各種樣式的驗(yàn)證碼。并且使用Kaptcha 生成驗(yàn)證碼也十分簡單,只需添加jar包,然后配置一下就可以使用。在配置中,可以自己定義驗(yàn)證碼字體的大小、顏色、樣式;驗(yàn)證碼圖片的大小、邊框、背景;驗(yàn)證碼的內(nèi)容范圍;驗(yàn)證碼的干擾線等等。
Kaptcha在Spring Boot中的使用
Kaptcha
- 導(dǎo)入jar包
- 編寫Kaptcha配置類
- 生成隨機(jī)字符、生成圖片
1. 在pom文件中導(dǎo)入jar包
<!-- Kaptcha Google驗(yàn)證碼工具-->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2. Kaptcha配置類
@Configuration
public class KaptchaConfig {
@Bean
public Producer kaptchaProducer() {
Properties properties = new Properties();
properties.setProperty("kaptcha.image.width","135");
properties.setProperty("kaptcha.image.height","55");
properties.setProperty("kaptcha.textproducer.font.size","32");
properties.setProperty("kaptcha.textproducer.font.color","0,0,0");
properties.setProperty("kaptcha.textproducer.char.string","0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
properties.setProperty("kaptcha.textproducer.char.length","4");
properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");
DefaultKaptcha kaptcha = new DefaultKaptcha();
Config config = new Config(properties);
kaptcha.setConfig(config);
return kaptcha;
}
}
3. 生成隨機(jī)字符串、生成圖片
在生成驗(yàn)證碼之前,我們先看看Kaptcha的核心
主要就是Producer
接口,這個(gè)接口中有兩個(gè)方法,分別是創(chuàng)建驗(yàn)證碼圖片和生成隨機(jī)驗(yàn)證碼。
編寫controller層代碼,返回驗(yàn)證碼圖片并將驗(yàn)證碼保存在session中,在用戶登錄時(shí)驗(yàn)證。文章來源:http://www.zghlxwxcb.cn/news/detail-835287.html
/**
* 獲取驗(yàn)證碼的方法
*/
@GetMapping("kaptcha")
public void getKaptcha(HttpServletResponse response, HttpSession session) {
// 生成驗(yàn)證碼
String text = kaptchaProducer.createText();
// 生成圖片
BufferedImage image = kaptchaProducer.createImage(text);
// 將驗(yàn)證碼存入session
session.setAttribute("kaptcha",text);
// 將圖片輸出給瀏覽器
response.setContentType("image/png");
try {
OutputStream outputStream = response.getOutputStream();
ImageIO.write(image,"png",outputStream);
} catch (IOException e) {
logger.error("響應(yīng)驗(yàn)證碼失敗:"+ e.getMessage());
}
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-835287.html
4. JavaScript
<script>
function refresh_kaptcha() {
var path = CONTEXT_PATH + "/kaptcha?p=" + Math.random();
$("#kaptcha").attr("src", path);
}
</script>
到了這里,關(guān)于Spring Boot利用Kaptcha生成驗(yàn)證碼的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!