Hutool-captcha 是 Hutool 工具包中的一個模塊,主要用于生成和驗證各種類型的驗證碼。
Hutool 是一個小而全的Java工具類庫,通過靜態(tài)方法封裝,降低了相關(guān)API的學(xué)習(xí)成本,提高了工作效率,使Java擁有函數(shù)式語言般的優(yōu)雅。
在Hutool工具包中,驗證碼功能位于cn.hutool.captcha包中,其核心接口為ICaptcha。
ICaptcha接口方法
createCode:創(chuàng)建驗證碼,實現(xiàn)類需同時生成隨機驗證碼字符串和驗證碼圖片。
getCode:獲取驗證碼的文字內(nèi)容。
verify:驗證驗證碼是否正確,建議忽略大小寫。
write:將驗證碼寫出到目標流中。
以下為springBoot項目中使用Hutool-captchat生成驗證碼并使用驗證碼的流程,主要有以下步驟
一、導(dǎo)入依賴
<!-- 驗證碼 --> <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);
// 驗證碼存入session
request.getSession().setAttribute("verifyCode", shearCaptcha);
// 輸出圖片流
shearCaptcha.write(response.getOutputStream());
}
}三、登錄前端頁面
<img src="/utils/captcha" onclick="this.src='/utils/captcha?id='+Math.random();" />

四、后端驗證碼驗證
@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", "驗證碼錯誤");
return "admin/login";
}
return "admin/index";
}
}