首先先引入hutool工具包
可以百度下载
后端代码
@RequestMapping("/getVerification")
@ILogInterceptor.LogMsg("获取验证码")
@ResponseBody
public void getVerification(HttpServletResponse response, HttpSession session) throws IOException{
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 4);
session.setAttribute("code",lineCaptcha.getCode());
try {
ServletOutputStream outputStream = response.getOutputStream();
lineCaptcha.write(outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping("/getVerificationTest")
@ILogInterceptor.LogMsg("验证验证码")
@ResponseBody
public boolean getVerificationTest(String str,HttpSession session) throws IOException{
boolean flag=false;
if(str.equals(session.getAttribute("code"))){
flag=true;
}
return flag;
}
验证码可以存取到seesion中,方便验证。生成的验证码可以是流也可以是文件形式。
前端代码
<div class="layui-form-item layui-input-wrap flex code-content">
<div class="layui-input-block">
<input type="text" name="text" placeholder="请输入验证码" autocomplete="off" id="value" required lay-verify="required"
class="user-pwd layui-input"/>
</div>
<img class="code" id="getProving" src=""></img>
</div>
//页面初始化加载验证码
$(document).ready(function(){
$.ajax({
url: "${base?js_string}/public/web/getVerification.action",
method: "POST",
success: function (result) {
$("#getProving").attr("src","${base?js_string}/public/web/getVerification.action")
}
});
});
// 获取-验证码
$(document).on('click', '#getProving', function () {
$.ajax({
url: "${base?js_string}/public/web/getVerification.action",
method: "POST",
success: function (result) {
$("#getProving").attr("src","${base?js_string}/public/web/getVerification.action")
}
})
});
// 验证-验证码
$(document).on('click', '#dl', function () {
localStorage.setItem('rememberPwd', $(".isRemember").prop("checked"));
$.ajax({
url: "${base?js_string}/public/web/getVerificationTest.action?str="+document.getElementById('value').value,
method: "POST",
success: function (result) {
if(result){
//$("#dologin").attr("action","/public/login/doLogin.do");
saveInfo();
$("#dologin").attr("action","${base?html}/public/login/doLogin.action");
$("#dologin").submit();
}
else {
layer.alert("验证码不匹配!");
return false;
}
},
})
|