验证码
导入jar包
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
config的配置
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
/**
* 验证码
*
* @author zhang
* @create 2021/9/10
*/
@Configuration
public class VerificationCode {
/**
* 验证码配置
*
* @return
*/
@Bean
public DefaultKaptcha getDefaultKaptcha() {
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
//是否有边框
properties.setProperty(Constants.KAPTCHA_BORDER, "yes");
//验证码文本颜色
properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue");
//验证码图片宽度
properties.setProperty(Constants.KAPTCHA_IMAGE_WIDTH, "160");
//验证码图片高度
properties.setProperty(Constants.KAPTCHA_IMAGE_HEIGHT, "60");
//文本字符大小
properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE, "50");
//验证码session的值
properties.setProperty(Constants.KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCode");
//验证码文本长度
properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "5");
//字体
properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_NAMES, "黑体,宋体,楷体,微软雅黑");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
controller的配置
// 验证码
@ResponseBody
@GetMapping("/identity")
public void getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
response.setContentType("image/jpeg");
String text = defaultKaptcha.createText();
//保存验证码在session当前会话
request.getSession().setAttribute("vrifyCode", text);
BufferedImage image = defaultKaptcha.createImage(text);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out);
out.flush();
out.close();
}
登录查询方法
@ResponseBody
@PostMapping("/dianxinl4")
private Result denglu(HttpServletRequest request, HttpServletResponse response, String AccountNumber, String password, String identityKey) {
String vrifyCode = (String) request.getSession().getAttribute("vrifyCode"); //获取到生成验证码存在session的验证码的值
String accountnumber = AccountNumber;// 账号
// 判断验证吗是否正确
if (vrifyCode.equalsIgnoreCase(identityKey)) { //比较验证吗
//查询是否拥有此账号
System.out.println(identityKey + "samlkfmsamffsd");
Yyuser yyuser = yyuserServicel.selectByPrimaryKey(accountnumber);
if (yyuser != null) {
password = MD5Util.getMD5(password);
if (password.equals(yyuser.getPassword().trim())) {
String name = yyuser.getAccount();
System.out.println(name);
request.getSession().setAttribute("name", name); //把查询到的用户信息返回值保存到session当前会话
return Result.suck(yyuser);
} else {
return Result.fail("密码错误");
}
} else {
return Result.fail("账号错误");
}
} else {
return Result.fail("验证码错误");
}
}
使用的工具类
**MD5加密**
import java.security.MessageDigest;
public class MD5Util {
public final static String getMD5(String s) {
char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try {
byte[] btInput = s.getBytes();
// 获得 MD5 摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
System.out.println(MD5Util.getMD5("aaa"));
System.out.println(MD5Util.getMD5("vvvv"));
}
}
定义的返回类
package com.zhang.utils;
import lombok.Data;
import java.io.Serializable;
/**
* @author zhang
* @date 2021年05月29日 下午 03:15
*/
@Data
public class Result implements Serializable {
private int code;//200是正常,非200表示异常
private String msg;
private Object data;
public static Result suck(Object data) {
return suck(200, "操作成功", data);
}
public static Result suck(int code, String msg, Object data) {
Result r = new Result();
r.setCode(code);
r.setMsg(msg);
r.setData(data);
return r;
}
/*异常*/
public static Result fail(String msg) {
return fail(400, msg, null);
}
public static Result fail(String msg, Object data) {
return fail(400, msg, data);
}
public static Result fail(int code, String msg, Object data) {
Result r = new Result();
r.setCode(code);
r.setMsg(msg);
r.setData(data);
return r;
}
}
页面设计
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<!-- 小图标 -->
<link href="/img/17960727_182401877000_2.jpg"
rel="shortcut icon"/>
<title>医院物资管理系统</title>
<link href="bootstrap-4.1.3-dist/css/bootstrap.min.css"
rel="stylesheet"/>
<link href="/layui/css/layui.css" rel="stylesheet"/>
<style>
.auth-wrapper {
min-height: 100vh;
position: relative;
background-size: cover;
}
</style>
</head>
<body>
<div class="container-fluid p-0">
<div class="auth-wrapper d-flex no-block justify-content-center align-items-center"
style="background-image: url('/img/登录图片.png');">
<div class="card"
style="background: #7cb1cf; width: 340px; margin-top: 10%;margin-left: 50%; height: 400px;">
<div class="card-body">
<span style="margin-left: 35%;"><img alt="" src="/img/23.png" style="width: 80px;height: 80px;"></span>
<!-- Form -->
<div class="row">
<div class="col-12">
<!-- 登录提交参数到方法的路径 -->
<form class="form-radius" id="formLogin" method="POST" onkeydown="onreturn()">
<!-- //th:action="@{/dianxinl}"-->
<div class="form-group form-row"
style="margin-top: 15px; color: red;">
<input class="UserID" name="UserID" type="hidden"
value="${tbuser.UserID}"/>
<!--隐藏元素存放ID-->
<label class="sr-only"> 用户名 </label>
<div class="col-12">
<div class="input-group">
<input class="form-control" id="AccountNumber" name="AccountNumber" placeholder="用户"
type="text"/>
</div>
<!-- -->
</div>
</div>
<div class="form-group form-row" style="margin-top: 15px">
<label class="sr-only"> 密码 </label>
<div class="col-12">
<div class="input-group">
<input class="form-control" id="password" name="password"
placeholder="密码" type="password"/>
</div>
</div>
</div>
<!-- 验证码 -->
<div class="form-group form-row" style="margin-top: 15px">
<label class="sr-only"> 验证码 </label>
<div class="col-8 ">
<div class="input-group">
<input class="form-control pword m-b" id="identityKey"
name="identityKey" placeholder="验证码" type="text"/>
<div class="input-group-addon p-0">
<div class="input-icon">
<!-- 验证码的路径 -->
<img alt="" id="imgIdentity"
onclick="resetIdentity()"
src="/identity"
style="margin-left: 198px; margin-top: -57px; height: 38px; width: 102px; border-radius: 5px 5px 5px 5px;">
</div>
</div>
</div>
</div>
</div>
<div class="form-group form-row justify-content-center">
<div class="col-10 ">
<div>
<button class="btn btn-danger btn-block" id="btnSubmit"
onclick="login()" type="button">登 录
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="/js/jquery.form.min.js" type="text/javascript"></script>
<script src="/js/jquery-3.2.1.min.js" type="text/javascript"></script>
<!-- layer弹窗 -->
<script src="/layui/layui.all.js" type="text/javascript"></script>
<script th:inline="none" type="text/javascript">
//回车登录
function onreturn() {
//点击的是否是回车键
if (window.event.keyCode === 13) {
//JS触发btnSubmit的单击事件
if (document.all('btnSubmit').click())
;
}
}
$(document).ready(function () {
});
function login() {
let AccountNumber = $("#AccountNumber").val();
let password = $("#password").val();
let identityKey = $("#identityKey").val();
$.post("/dianxinl4", {
AccountNumber: AccountNumber,
password: password,
identityKey: identityKey
}, function (data) {
console.log(data)
if (data.data != null) {
var name = data.data.account;
layer.msg(data.msg, {
title: '提示',
icon: 6
});
window.location.href = "/zheye";//?name=+ data.data.account
} else {
layer.msg(data.msg, {
title: '提示',
icon: 2
});
resetIdentity();
}
})
}
//验证码
function resetIdentity() {
$("#imgIdentity").attr("src",
"/identity?t=" + new Date().getTime());
}
</script>
</body>
</html>
效果图