一、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)