0、展示
源码:https://gitee.com/whvse/EasyCaptcha
一、引入依赖
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>1.6.2</version>
</dependency>
二、后端接口
// 以流的方式向前端输出验证码图片
@RequestMapping("/captcha")
public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
CaptchaUtil.out(request, response);
}
// 判断验证码是否正确
@RequestMapping("/checkCaptcha")
public String checkCaptcha(HttpServletRequest request,String verCode) {
if (!CaptchaUtil.ver(verCode, request)) {
CaptchaUtil.clear(request); // 清除session中的验证码
return "验证码不正确";
}
return "200";
}
三、前端
<body>
<div class="login">
<div class="message">农业温湿度管理系统</div>
<div id="darkbannerwrap"></div>
<form id="form1" action="" method="post" class="layui-form" lay-filter="example" onsubmit="return false;">
<input id="username" name="username" placeholder="用户名" type="text"
autocomplete="off" lay-verify="required">
<hr class="hr15">
<input id="password" name="password" placeholder="密码" type="password"
autocomplete="off" lay-verify="required">
<hr class="hr15">
<input id="verCode" name="verCode" placeholder="验证码" type="text"
autocomplete="off" lay-verify="required" style="width:150px;">
<img id="captcha" src="/captcha" width="130px" height="35px" onclick="changeCap()"/>
<hr class="hr15">
<button style="width: 100%;" onclick="login()" lay-submit="">登录</button>
<hr class="hr20">
<span id="info" style="color: red"></span>
</form>
<button style="width: 100%;" type="button" onclick="location='register1.html'">注册</button>
</div>
<script>
//声明form,用于检验
layui.use(['form','layer'], function(){
form = layui.form;
$ = layui.jquery;
});
function changeCap() {
document.getElementById("captcha").src="/captcha?date="+new Date().getTime();
}
function login() {
var username = $('#username').val();
var password = $('#password').val();
var verCode = $('#verCode').val();
//判断验证码
$.ajax({
type : 'get',
url : '/checkCaptcha',
data : {verCode:verCode},
success : function(data) {
if (data === "200") {
//登录
$.ajax({
type : 'post',
url : '/login',
data : {username:username,password:password},
success : function(data) {
//console.log(data);
window.location.href = "/";
}
})
}else {
//提示层
layer.msg('验证码错误', {
time: 1500 //1.5s后自动关闭
});
document.getElementById("captcha").src="/captcha?date="+new Date().getTime();
}
}
})
}
</script>
</body>