目录
一、验证码的作用及分类
注册、登录时,验证码(CAPTCHA):用于区分人还是计算机的自动程序,可以有效防止特定程序(爬虫)以特定方式不断的进行登录或者注册。从而提高系统的安全性;
分类:输入、拖拽、图片识别
三、验证原理
验证码是java程序生成的一张图片、 通过流的形式展示到页面上;
判断用户输入的验证码与程序生成的验证码是否相等。
由于验证码的生成和校验是两次请求,故将程序验证码需存入Session中。
四、使用一些工具生成验证码及校验
4.1 ,使用hutool
导入依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.11</version>
</dependency>
createCode
创建验证码,实现类需同时生成随机验证码字符串和验证码图片getCode
获取验证码的文字内容verify
验证验证码是否正确,建议忽略大小写write
将验证码写出到目标流中
其中write方法只有一个OutputStream
,ICaptcha
实现类可以根据这个方法封装写出到文件等方法。
新建请求接口
/**
* 获取验证码
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/captcha")
public void captcha(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
ICaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 4);
// 获取验证码的文字内容存入session
session.setAttribute("captcha",captcha.getCode());
ServletOutputStream outputStream = response.getOutputStream();
captcha.write(outputStream);
outputStream.close();
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>hello,hutool</h1>
<h1 th:text="${flag}"></h1>
<form method="post" action="/checkCode">
<div >
<input type="text" name="captcha" placeholder="输入验证码" autocomplete="off" required>
<img th:src="@{/captcha}" id="captcha" >
</div>
<div>
<input type="submit" />
</div>
</form>
</body>
</html>
效果
校验
/**
* 校验验证码
* @param captcha
*/
@PostMapping("/checkCode")
public String checkCode(String captcha, Model model,HttpSession session){
//取出session中的验证码
String captcha1 = (String) session.getAttribute("captcha");
session.removeAttribute("captcha");
//忽略大小写比较
String s1 = captcha.toLowerCase();
String s2 = captcha1.toLowerCase();
if(s1.equals(s2)){
model.addAttribute("flag",true);
// todo
}else {
model.addAttribute("flag",false);
// todo
}
return "index";
}
4.2,使用easy-captcha
导入依赖
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>1.6.2</version>
</dependency>
生成验证码
/**
* 获取验证码
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/captcha")
public void captcha(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
CaptchaUtil.out(request,response);
}
效果:
校验
/**
* 校验验证码
* @param captcha
*/
@PostMapping("/checkCode")
public String checkCode(String captcha, Model model,HttpServletRequest request){
if(!CaptchaUtil.ver(captcha, request)){
CaptchaUtil.clear(request);
model.addAttribute("flag",false);
}
return "index";
}
五、单击图片切换
<script th:src="@{https://cdn.jsdelivr.net/npm/jquery@3.2/dist/jquery.min.js}"></script>
<script th:inline="javascript">
//点击验证码换图
$("#captcha").click(function(){
$("#captcha").attr("src",'captcha?date='+new Date().getTime());
});
</script>