Kaptcha验证码的简单使用
作用
防止不法分子在短时间内使用机器人进行批量的重读操作。如果设置了验证码,可以减轻上述操作对系统的危害。
springboot集成Kaptcha
-
添加依赖
<dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
-
配置
在spring项目的config包中新建对应的配置类
@Component public class KaptchaConfig { @Bean public DefaultKaptcha getDefaultKaptcha(){ com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha(); Properties properties = new Properties(); // 图片边框 properties.put("kaptcha.border", "no"); // 字体颜色 properties.put("kaptcha.textproducer.font.color", "black"); // 图片宽 properties.put("kaptcha.image.width", "160"); // 图片高 properties.put("kaptcha.image.height", "40"); // 字体大小 properties.put("kaptcha.textproducer.font.size", "30"); // 验证码长度 properties.put("kaptcha.textproducer.char.space", "5"); // 字体 properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑"); Config config = new Config(properties); defaultKaptcha.setConfig(config); return defaultKaptcha; } }
生成与显示
通过一个session记录相关的验证码信息,并且通过一个response对象返回验证码图片给前端
@Controller
public class KaptchaController {
@Autowired
private DefaultKaptcha captchaProducer;
@GetMapping("/kaptcha")
public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
byte[] captchaOutputStream = null;
ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
try {
//生产验证码字符串并保存到session中
String verifyCode = captchaProducer.createText();
httpServletRequest.getSession().setAttribute("verifyCode", verifyCode);
BufferedImage challenge = captchaProducer.createImage(verifyCode);
ImageIO.write(challenge, "jpg", imgOutputStream);
} catch (IllegalArgumentException e) {
httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
captchaOutputStream = imgOutputStream.toByteArray();
httpServletResponse.setHeader("Cache-Control", "no-store");
httpServletResponse.setHeader("Pragma", "no-cache");
httpServletResponse.setDateHeader("Expires", 0);
httpServletResponse.setContentType("image/jpeg");
ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
responseOutputStream.write(captchaOutputStream);
responseOutputStream.flush();
responseOutputStream.close();
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>验证码显示</title>
</head>
<body>
<img src="/kaptcha"
onclick="this.src='/kaptcha?d='+new Date()*1">
</body>
</html>
在谷歌浏览器中可以看出每次点击都会生成一个新的验证码
使用
编写一个带请求参数的controller,将该参数与session中的验证码字符串进行比较
@GetMapping("/verify")
@ResponseBody
public String verify(@RequestParam("code") String code, HttpSession session) {
if (StringUtils.isEmpty(code)) {
return "验证码不能为空";
}
String kaptchaCode = session.getAttribute("verifyCode") + "";
if (StringUtils.isEmpty(kaptchaCode) || !code.equals(kaptchaCode)) {
return "验证码错误";
}
return "验证成功";
}
单单一个验证码部分,我们可以使用异步的AJAX
按下提交按钮后,js方法会获取键入的值来进行AJAX请求
<script type="text/javascript">
$(function () {
$("#verify").click(function () {
var code = $("#code").val();
$.ajax({
type: 'GET',//方法类型
url: '/verify?code=' + code,
success: function (result) {
alert(result);
},
error: function () {
alert("请求失败");
}
});
})
});
</script>
最后,大功告成!!
error: function () {
alert("请求失败");
}
});
})
});
~~~
最后,大功告成!!