springboot驗證碼的生成與驗證的兩種方法
前言
在springboot的登陸頁面中為了防止機器大規(guī)模注冊,機器暴力破解數(shù)據(jù)密碼等危害,需要驗證隨機生成的驗證碼?,F(xiàn)提出兩種簡易方案生成驗證碼功能,一種采用springboot整合kaptcha第三方驗證碼生成工具的生成方案;另一種采用springboot整合第三方類庫hutool生成驗證碼,驗證成功跳轉(zhuǎn)至success頁面,失敗則跳轉(zhuǎn)false頁面?;緦崿F(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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java數(shù)據(jù)結(jié)構(gòu)之KMP算法詳解以及代碼實現(xiàn)
KMP算法是一種改進的字符串匹配算法,核心是利用之前的匹配失敗時留下的信息,選擇最長匹配長度直接滑動,從而減少匹配次數(shù)。本文主要介紹了KMP算法的原理與實現(xiàn),需要的可以參考一下2022-12-12
Spring Boot實現(xiàn)Undertow服務器同時支持HTTP2、HTTPS的方法
這篇文章考慮如何讓Spring Boot應用程序同時支持HTTP和HTTPS兩種協(xié)議。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12
Java8 自定義CompletableFuture的原理解析
這篇文章主要介紹了Java8 自定義CompletableFuture的原理解析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
Java中使用同步回調(diào)和異步回調(diào)的示例詳解
這篇文章主要介紹了Java中使用同步回調(diào)和異步回調(diào)的相關資料,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04
mybatis中association和collection的使用與區(qū)別
在 MyBatis 中,<association>?和?<collection>?是用于配置結(jié)果映射中關聯(lián)關系的兩個元素,本文主要介紹了mybatis中<association>和<collection>的使用與區(qū)別,具有一定的參考價值,感興趣的可以了解一下2024-01-01

