springboot驗(yàn)證碼的生成與驗(yàn)證的兩種方法
前言
在springboot的登陸頁(yè)面中為了防止機(jī)器大規(guī)模注冊(cè),機(jī)器暴力破解數(shù)據(jù)密碼等危害,需要驗(yàn)證隨機(jī)生成的驗(yàn)證碼?,F(xiàn)提出兩種簡(jiǎn)易方案生成驗(yàn)證碼功能,一種采用springboot整合kaptcha第三方驗(yàn)證碼生成工具的生成方案;另一種采用springboot整合第三方類庫(kù)hutool生成驗(yàn)證碼,驗(yàn)證成功跳轉(zhuǎn)至success頁(yè)面,失敗則跳轉(zhuǎn)false頁(yè)面?;緦?shí)現(xiàn)方案如下:
效果一覽(單擊圖片刷新驗(yàn)證碼)

一、使用整合kaptcha方式實(shí)現(xiàn)驗(yàn)證碼生成與驗(yàn)證
kaptcha是一個(gè)可高度適配的使用驗(yàn)證碼生成工具,Kaptcha詳細(xì)配置表如下:
參考博客:Kaptcha
| Constant | description | default |
|---|---|---|
| kaptcha.border | 圖片邊框,合法值:yes,no | yes |
| kaptcha.border.color | 邊框顏色,合法值: r,g,b (and optional alpha) 或者 white,black,blue. | black |
| kaptcha.image.width | 圖片寬 | 200 |
| kaptcha.image.height | 圖片高 | 50 |
| kaptcha.producer.impl | 圖片實(shí)現(xiàn)類 | com.google.code.kaptcha.impl.DefaultKaptcha |
| kaptcha.textproducer.impl | 文本實(shí)現(xiàn)類 | com.google.code.kaptcha.text.impl.DefaultTextCreator |
| kaptcha.textproducer.char.string | 文本集合,驗(yàn)證碼值從此集合中獲取 | abcde2345678gfynmnpwx |
| kaptcha.textproducer.char.length | 驗(yàn)證碼長(zhǎng)度 | 5 |
| kaptcha.textproducer.font.names | 字體 | Arial, Courier |
| kaptcha.textproducer.font.size | 字體大小 | 40px. |
| kaptcha.textproducer.font.color | 字體顏色,合法值: r,g,b 或者 white,black,blue. | black |
| kaptcha.textproducer.char.space | 文字間隔 | 2 |
| kaptcha.noise.impl | 干擾實(shí)現(xiàn)類 | com.google.code.kaptcha.impl.DefaultNoise |
| kaptcha.noise.color | 干擾 顏色,合法值: r,g,b 或者 white,black,blue. | black |
| kaptcha.obscurificator.impl | 圖片樣式: 水紋 com.google.code.kaptcha.impl.WaterRipple 魚眼 com.google.code.kaptcha.impl.FishEyeGimpy 陰影 com.google.code.kaptcha.impl.ShadowGimpy | com.google.code.kaptcha.impl.WaterRipple |
| kaptcha.background.impl | 背景實(shí)現(xiàn)類 | com.google.code.kaptcha.impl.DefaultBackground |
| kaptcha.background.clear.from | 背景顏色漸變,開始顏色 | light grey |
| kaptcha.background.clear.to | 背景顏色漸變, 結(jié)束顏色 | white |
| kaptcha.word.impl | 文字渲染器 | com.google.code.kaptcha.text.impl.DefaultWordRenderer |
| kaptcha.session.key | session key | KAPTCHA_SESSION_KEY |
| kaptcha.session.date | session date | KAPTCHA_SESSION_DATE |
1.1 pom文件中導(dǎo)入kaptcha依賴
?? 新建springboot項(xiàng)目,并在其pom.xml中導(dǎo)入kaptcha依賴:
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
1.2 創(chuàng)建前端頁(yè)面與跳轉(zhuǎn)頁(yè)面
?? 前端頁(yè)面index.html
<h2>kaptcha驗(yàn)證碼驗(yàn)證</h2>
<form action="/loginh" method="post">
<input type="text" name="verifyCode" placeholder="請(qǐng)輸入驗(yàn)證碼" required="true">
<img alt="單擊圖片刷新!" class="pointer" src="/common/kaptcha"
onclick="this.src='/common/kaptcha?d='+new Date()*1">
</br>
<button type="submit" value="submit">登陸</button>
</form>
?? 跳轉(zhuǎn)頁(yè)面success.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>success</h2>
</body>
</html>
1.3 實(shí)現(xiàn)后端代碼
1.3.1 注入keptcha配置類
?? 創(chuàng)建配置類KaptchaConfig.java
package com.allin.config;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.Properties;
@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.put("kaptcha.border", "no");
properties.put("kaptcha.textproducer.font.color", "black");
properties.put("kaptcha.image.width", "150");
properties.put("kaptcha.image.height", "40");
properties.put("kaptcha.textproducer.font.size", "30");
properties.put("kaptcha.session.key", "verifyCode");
properties.put("kaptcha.textproducer.char.space", "5");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
1.3.2 創(chuàng)建后端控制類生成驗(yàn)證碼
?? 創(chuàng)建控制類CommonController類,一方面通過(guò)流的方式將隨機(jī)生成的驗(yàn)證碼圖片信息發(fā)送到前端瀏覽器;另一方面將驗(yàn)證碼中的驗(yàn)證信息寫入session中,以方便后續(xù)的驗(yàn)證
package com.allin.controller;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
@Controller
public class CommonController {
@Autowired
private DefaultKaptcha captchaProducer;
@GetMapping("/common/kaptcha")
public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
byte[] captchaOutputStream = null;
ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
try {
//生產(chǎn)驗(yàn)證碼字符串并保存到session中
String verifyCode = captchaProducer.createText();
httpServletRequest.getSession().setAttribute("verifyCode", verifyCode);
BufferedImage challenge = captchaProducer.createImage(verifyCode);
ImageIO.write(challenge, "jpg", imgOutputStream);
} catch (IllegalArgumentException e) {
httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
captchaOutputStream = imgOutputStream.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(captchaOutputStream);
responseOutputStream.flush();
responseOutputStream.close();
}
}
1.3.3 實(shí)現(xiàn)驗(yàn)證碼的驗(yàn)證與頁(yè)面跳轉(zhuǎn)
?? 對(duì)前端輸入的數(shù)據(jù)并發(fā)送到服務(wù)器的驗(yàn)證信息進(jìn)行校驗(yàn),當(dāng)輸入信息與驗(yàn)證碼信息一致則跳轉(zhuǎn)至success.html頁(yè)面,否則跳轉(zhuǎn)至false.html頁(yè)面
@Controller
public class AdminController {
@PostMapping("/loginh")
public String loginByKaptcha(@RequestParam("verifyCode") String verifyCode,
HttpSession session){
String kaptchaCode = session.getAttribute("verifyCode") + "";
if(verifyCode.equals(kaptchaCode)){
return "success";
}
return "false";
}
}
二、使用hutool-captcha方式實(shí)現(xiàn)驗(yàn)證碼生成與驗(yàn)證
??Hutool是一個(gè)Java工具包,也只是一個(gè)工具包,它幫助我們簡(jiǎn)化每一行代碼,減少每一個(gè)方法,讓Java語(yǔ)言也可以“甜甜的”。Hutool最初是我項(xiàng)目中“util”包的一個(gè)整理,后來(lái)慢慢積累并加入更多非業(yè)務(wù)相關(guān)功能,并廣泛學(xué)習(xí)其它開源項(xiàng)目精髓,經(jīng)過(guò)自己整理修改,最終形成豐富的開源工具集

2.1 pom文件中導(dǎo)入hutool-captcha依賴
?? 新建springboot項(xiàng)目,并在其pom.xml中導(dǎo)入hutool-captcha依賴:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.1</version>
</dependency>
2.2 創(chuàng)建前端頁(yè)面與跳轉(zhuǎn)頁(yè)面
?? 前端頁(yè)面index.html
<h2>Hutool-captcha驗(yàn)證碼驗(yàn)證</h2>
<form action="/loginc" method="post">
<input type="text" name="verifyCode" placeholder="請(qǐng)輸入驗(yàn)證碼" required="true">
<img alt="單擊圖片刷新!" class="pointer" src="/common/verify"
onclick="this.src='/common/verify?d='+new Date()*1">
</br>
<button type="submit" value="submit">登陸</button>
</form>
?? 跳轉(zhuǎn)頁(yè)面success.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>success</h2>
</body>
</html>
2.3 實(shí)現(xiàn)后端代碼
2.3.1 創(chuàng)建后端控制類生成驗(yàn)證碼
?? 創(chuàng)建控制類CommonController類,一方面通過(guò)流的方式將隨機(jī)生成的驗(yàn)證碼圖片信息發(fā)送到前端瀏覽器;另一方面將驗(yàn)證碼中的驗(yàn)證信息寫入session中,以方便后續(xù)的驗(yàn)證
@RestController
public class HutoolController {
@GetMapping("/common/verify")
public void Verify(HttpServletRequest request,HttpServletResponse response) throws IOException {
//定義圖形驗(yàn)證碼的長(zhǎng)、寬、驗(yàn)證碼字符數(shù)、干擾線寬度
ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(150, 40, 5, 4);
//圖形驗(yàn)證碼寫出,可以寫出到文件,也可以寫出到流
captcha.write(response.getOutputStream());
//獲取驗(yàn)證碼中的文字內(nèi)容
String verifyCode = captcha.getCode();
request.getSession().setAttribute("verifyCode",verifyCode);
}
2.3.2 實(shí)現(xiàn)驗(yàn)證碼的驗(yàn)證與頁(yè)面跳轉(zhuǎn)
?? 對(duì)前端輸入的數(shù)據(jù)并發(fā)送到服務(wù)器的驗(yàn)證信息進(jìn)行校驗(yàn),當(dāng)輸入信息與驗(yàn)證碼信息一致則跳轉(zhuǎn)至success.html頁(yè)面,否則跳轉(zhuǎn)至false.html頁(yè)面
@Controller
public class AdminController {
@PostMapping("/loginc")
public String loginByHutool(@RequestParam("verifyCode") String verifyCode,
HttpSession session){
String captchaCode = session.getAttribute("verifyCode") + "";
if(verifyCode.equals(captchaCode)){
return "success";
}
return "false";
}
}
到此這篇關(guān)于springboot驗(yàn)證碼的生成與驗(yàn)證的兩種方法的文章就介紹到這了,更多相關(guān)springboot驗(yàn)證碼生成驗(yàn)證 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mybatis 如何批量刪除數(shù)據(jù)的實(shí)現(xiàn)示例
這篇文章主要介紹了Mybatis 如何批量刪除數(shù)據(jù)的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
SpringBoot整合WebSocket實(shí)現(xiàn)后端向前端發(fā)送消息的實(shí)例代碼
WebSocket使得客戶端和服務(wù)器之間的數(shù)據(jù)交換變得更加簡(jiǎn)單,允許服務(wù)端主動(dòng)向客戶端推送數(shù)據(jù),下面這篇文章主要給大家介紹了關(guān)于SpringBoot整合WebSocket實(shí)現(xiàn)后端向前端發(fā)送消息的相關(guān)資料,需要的朋友可以參考下2023-03-03
RocketMQ生產(chǎn)者一個(gè)應(yīng)用不能發(fā)送多個(gè)NameServer消息解決
這篇文章主要為大家介紹了RocketMQ生產(chǎn)者一個(gè)應(yīng)用不能發(fā)送多個(gè)NameServer消息原因及解決方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
MyBatis后端對(duì)數(shù)據(jù)庫(kù)進(jìn)行增刪改查等操作實(shí)例
Mybatis是appach下開源的一款持久層框架,通過(guò)xml與java文件的緊密配合,避免了JDBC所帶來(lái)的一系列問(wèn)題,下面這篇文章主要給大家介紹了關(guān)于MyBatis后端對(duì)數(shù)據(jù)庫(kù)進(jìn)行增刪改查等操作的相關(guān)資料,需要的朋友可以參考下2022-08-08
Java服務(wù)假死后續(xù)之內(nèi)存溢出的原因分析
這篇文章主要介紹了Java服務(wù)假死后續(xù)之內(nèi)存溢出,本文給大家分享原因排查和故障解決方法,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07
永中文檔在線轉(zhuǎn)換服務(wù)Swagger調(diào)用說(shuō)明
這篇文章主要為大家介紹了永中文檔在線轉(zhuǎn)換服務(wù)Swagger調(diào)用說(shuō)明,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
Spring中的Schedule動(dòng)態(tài)添加修改定時(shí)任務(wù)詳解
這篇文章主要介紹了Spring中的Schedule動(dòng)態(tài)添加修改定時(shí)任務(wù)詳解,可能有人會(huì)問(wèn),為啥不用Quartz,Quartz自然是非常方便強(qiáng)大的,但不是本篇要講的內(nèi)容,本篇就偏要使用SpringSchedule來(lái)實(shí)現(xiàn)動(dòng)態(tài)的cron表達(dá)式任務(wù),需要的朋友可以參考下2023-11-11

