sprinbgoot 验证码(算术型和字符型)解析
接上篇讲
直接上干货吧
1.完整的前端源码
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
html,body{
width: 100%;
height: 100%;
margin: 0 auto;
}
a{text-decoration:none}
</style>
<body>
<a href="javascript:void(0);">
<img th:src="@{/captcha/captchaImage(type='math')}" class="imgcode">
</a>
</br></br></br>
结果:<input id="verification">
<button id="sub">提交</button>
</body>
<!--内联语法的运用:相当于ctx="/"-->
<script th:inline="javascript"> var ctx = [[@{/}]]; </script>
<script src="https://cdn.bootcss.com/jquery/2.2.3/jquery.min.js"></script>
<script>
$(function () {
console.log("1");
imgCodeRefresh();
//利用ajax提交到后端:成功或失败后返回信息
$('#sub').click(function () {
$.post(ctx + 'captcha/verificationCaptchaResult',{"verification":$('#verification').val()},function (data) {
if(data == 'success'){
console.log("验证成功");
alert("验证成功");
}else{
console.log("验证失败");
alert("验证失败");
imgCodeRefresh();
}
});
});
});
//点击图片刷新
function imgCodeRefresh(){
$('.imgcode').click(function() {
console.log("2");
var url = ctx + "captcha/captchaImage?type=" + "math" + "&s=" + Math.random();
//设置imgcode要传给控制器的src值为url
$(".imgcode").attr("src", url);
});
}
</script>
</html>
随便先拿一个效果图用来讲一下前端,如下图片所示
点击图片切换验证码是imgCodeRefresh();将src的值切换,然后传到控制器,然后通过我上一篇的讲解来生成二维码。
结果:<input id="verification">
<button id="sub">提交</button>
用户输入验证码,然后提交执行下面代码,传到前端。
$(’#sub’).click(function () { xxxx});
2.解析(后端部分代码)
@PostMapping("/verificationCaptchaResult")
@ResponseBody
public String verificationCaptchaResult(HttpServletRequest request){
System.out.println("开始验证");
String sessionCode = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
String code = request.getParameter("verification");
if(code.equals(sessionCode)){
System.out.println("验证成功");
return "success";
}else{
System.out.println("验证失败");
return "error";
}
}
很简单是不是,用户输入的值和code(前面注释中有意思:生成二维码的值)进行比较,把验证结果返回前端,然后弹出信息,如下代码所示
if(data == 'success'){
console.log("验证成功");
alert("验证成功");
}else{
console.log("验证失败");
alert("验证失败");
imgCodeRefresh();
}
有什么不理解的留言就行,现在源码还在审核,需要源码留言