一、EasyCaptcha簡介
Java圖形驗證碼,支持gif、中文、算術等類型,可用於Java Web、JavaSE等項目。
開源地址 https://github.com/whvcse/EasyCaptcha
二、SpringBoot項目如何使用
1、初始化一個基本的SpringBoot項目
2、引入EasyCaptcha 依賴
<dependency> <groupId>com.github.whvcse</groupId> <artifactId>easy-captcha</artifactId> <version>1.6.2</version> </dependency>
3、生成驗證碼
@RequestMapping("/captcha") public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception{ GifCaptcha gifCaptcha = new GifCaptcha(130,48,4); CaptchaUtil.out(gifCaptcha, request, response); String verCode = gifCaptcha.text().toLowerCase(); request.getSession().setAttribute("CAPTCHA",verCode); //存入session }
4、校驗驗證碼
public class LoginController { private static final Logger log = LoggerFactory.getLogger(LoginController.class); @GetMapping("/") public String login() { return "/test"; } @PostMapping("/test") public String test(HttpServletRequest request, HttpServletResponse response) { String username = request.getParameter("username"); String password = request.getParameter("password"); String captcha = request.getParameter("code"); String sessionCode = request.getSession().getAttribute("CAPTCHA").toString(); if(sessionCode == null ||StringUtils.isEmpty(sessionCode)){ return "驗證碼為空"; } if(captcha.equals(sessionCode)){ return "驗證通過"; } return "驗證失敗"; } }
5、前端html中頁面代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="./lib/jquery/1.9.1/jquery.min.js"></script> </head> <body> <div> <form action="http://localhost:8088/test" method="post"> <div> <label>用戶名</label> <input type="text" name="username" id="username"> <label>密碼</label> <input type="password" name="password" id="password"> <label>驗證碼</label> <img src="/captcha" height="48px" width="130px"> <input type="text" name="code" id="code"> <input type="submit" value="登錄"> </div> </form> </div> </body> </html>
ref:EasyCaptcha: Java圖形驗證碼,支持gif、中文、算術等類型,可用於Java Web、JavaSE等項目。 (gitee.com)