Hutool-captcha 是 Hutool 工具包中的一個(gè)模塊,主要用于生成和驗(yàn)證各種類型的驗(yàn)證碼。
Hutool 是一個(gè)小而全的Java工具類庫,通過靜態(tài)方法封裝,降低了相關(guān)API的學(xué)習(xí)成本,提高了工作效率,使Java擁有函數(shù)式語言般的優(yōu)雅。
在Hutool工具包中,驗(yàn)證碼功能位于cn.hutool.captcha包中,其核心接口為ICaptcha。
ICaptcha接口方法
createCode:創(chuàng)建驗(yàn)證碼,實(shí)現(xiàn)類需同時(shí)生成隨機(jī)驗(yàn)證碼字符串和驗(yàn)證碼圖片。
getCode:獲取驗(yàn)證碼的文字內(nèi)容。
verify:驗(yàn)證驗(yàn)證碼是否正確,建議忽略大小寫。
write:將驗(yàn)證碼寫出到目標(biāo)流中。
以下為springBoot項(xiàng)目中使用Hutool-captchat生成驗(yàn)證碼并使用驗(yàn)證碼的流程,主要有以下步驟
一、導(dǎo)入依賴
<!-- 驗(yàn)證碼 --> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-captcha</artifactId> <version>5.8.7</version> </dependency>
二、控制類
import cn.hutool.captcha.CaptchaUtil; import cn.hutool.captcha.ShearCaptcha; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Controller public class Captcha { @GetMapping("utils/captcha") public void getCaptcha(HttpServletResponse response, HttpServletRequest request) throws IOException { response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/png"); ShearCaptcha shearCaptcha= CaptchaUtil.createShearCaptcha(150, 30, 4, 2); // 驗(yàn)證碼存入session request.getSession().setAttribute("verifyCode", shearCaptcha); // 輸出圖片流 shearCaptcha.write(response.getOutputStream()); } }
三、登錄前端頁面
<img src="/utils/captcha" onclick="this.src='/utils/captcha?id='+Math.random();" />
四、后端驗(yàn)證碼驗(yàn)證
@Controller @RequestMapping("/admin") public class AdminController { @PostMapping(value = "/login") public String login(@RequestParam("userName") String userName, @RequestParam("password") String password, @RequestParam("verifyCode") String verifyCode, HttpSession session) { ShearCaptcha shearCaptcha = (ShearCaptcha) session.getAttribute("verifyCode"); if (shearCaptcha == null || !shearCaptcha.verify(verifyCode)) { session.setAttribute("errorMsg", "驗(yàn)證碼錯(cuò)誤"); return "admin/login"; } return "admin/index"; } }