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

一、使用整合kaptcha方式實現(xiàn)驗證碼生成與驗證
kaptcha是一個可高度適配的使用驗證碼生成工具,Kaptcha詳細配置表如下:
參考博客: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 | 圖片實現(xiàn)類 | com.google.code.kaptcha.impl.DefaultKaptcha |
| kaptcha.textproducer.impl | 文本實現(xiàn)類 | com.google.code.kaptcha.text.impl.DefaultTextCreator |
| kaptcha.textproducer.char.string | 文本集合,驗證碼值從此集合中獲取 | abcde2345678gfynmnpwx |
| kaptcha.textproducer.char.length | 驗證碼長度 | 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 | 干擾實現(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 | 背景實現(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文件中導入kaptcha依賴
?? 新建springboot項目,并在其pom.xml中導入kaptcha依賴:
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
1.2 創(chuàng)建前端頁面與跳轉(zhuǎn)頁面
?? 前端頁面index.html
<h2>kaptcha驗證碼驗證</h2>
<form action="/loginh" method="post">
<input type="text" name="verifyCode" placeholder="請輸入驗證碼" 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)頁面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 實現(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)建后端控制類生成驗證碼
?? 創(chuàng)建控制類CommonController類,一方面通過流的方式將隨機生成的驗證碼圖片信息發(fā)送到前端瀏覽器;另一方面將驗證碼中的驗證信息寫入session中,以方便后續(xù)的驗證
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)驗證碼字符串并保存到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 實現(xiàn)驗證碼的驗證與頁面跳轉(zhuǎn)
?? 對前端輸入的數(shù)據(jù)并發(fā)送到服務器的驗證信息進行校驗,當輸入信息與驗證碼信息一致則跳轉(zhuǎn)至success.html頁面,否則跳轉(zhuǎn)至false.html頁面
@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方式實現(xiàn)驗證碼生成與驗證
??Hutool是一個Java工具包,也只是一個工具包,它幫助我們簡化每一行代碼,減少每一個方法,讓Java語言也可以“甜甜的”。Hutool最初是我項目中“util”包的一個整理,后來慢慢積累并加入更多非業(yè)務相關功能,并廣泛學習其它開源項目精髓,經(jīng)過自己整理修改,最終形成豐富的開源工具集

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

