Springboot实现验证码登录
Springboot实现验证码登录
1.背景
本人近期正在完成毕业设计(旅游信息管理系统)的制作,采用的SpringBoot+Thymeleaf的模式。在登录网站时想要添加验证码验证,通过网上查找资料,决定整合Kaptcha来实现验证码登录
2.过程
后端代码
2.1 在pom.xml中导入Kaptcha和ajax依赖
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/cljs-ajax/cljs-ajax -->
<dependency>
<groupId>cljs-ajax</groupId>
<artifactId>cljs-ajax</artifactId>
<version>0.8.1</version>
</dependency>
这里我用的是Maven项目,非Maven的可以下载相关的jar包;
2.2 新建kaptchaConfig类,配置kaptcha
@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.setProperty("kaptcha.border", "no");
// 边框颜色
properties.setProperty("kaptcha.border.color", "black");
//边框厚度
properties.setProperty("kaptcha.border.thickness", "1");
// 图片宽
properties.setProperty("kaptcha.image.width", "200");
// 图片高
properties.setProperty("kaptcha.image.height", "50");
//图片实现类
properties.setProperty("kaptcha.producer.impl", "com.google.code.kaptcha.impl.DefaultKaptcha");
//文本实现类
properties.setProperty("kaptcha.textproducer.impl", "com.google.code.kaptcha.text.impl.DefaultTextCreator");
//文本集合,验证码值从此集合中获取
properties.setProperty("kaptcha.textproducer.char.string", "01234567890");
//验证码长度
properties.setProperty("kaptcha.textproducer.char.length", "4");
//字体
properties.setProperty("kaptcha.textproducer.font.names", "宋体");
//字体颜色
properties.setProperty("kaptcha.textproducer.font.color", "black");
//文字间隔
properties.setProperty("kaptcha.textproducer.char.space", "3");
//干扰实现类
properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.DefaultNoise");
//干扰颜色
properties.setProperty("kaptcha.noise.color", "blue");
//干扰图片样式
properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.WaterRipple");
//背景实现类
properties.setProperty("kaptcha.background.impl", "com.google.code.kaptcha.impl.DefaultBackground");
//背景颜色渐变,结束颜色
properties.setProperty("kaptcha.background.clear.to", "white");
//文字渲染器
properties.setProperty("kaptcha.word.impl", "com.google.code.kaptcha.text.impl.DefaultWordRenderer");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
2.3 新建CommonUtil工具类
public class CommonUtil {
/**
* 生成验证码图片
* @param request 设置session
* @param response 转成图片
* @param captchaProducer 生成图片方法类
* @param validateSessionKey session名称
* @throws Exception
*/
public static void validateCode(HttpServletRequest request, HttpServletResponse response, DefaultKaptcha captchaProducer, String validateSessionKey) throws Exception{
// Set to expire far in the past.
response.setDateHeader("Expires", 0);
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
// return a jpeg
response.setContentType("image/jpeg");
// create the text for the image
String capText = captchaProducer.createText();
// store the text in the session
request.getSession().setAttribute(validateSessionKey, capText);
// create the image with the text
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
// write the data out
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
}
}
2.4 编写控制层代码,新建MainController类
@Controller
public class MainController {
@Resource
private DefaultKaptcha captchaProducer;
@RequestMapping(value = {"/"})
public String index() {
return "/index";
}
/**
* 登录验证码SessionKey
*/
public static final String LOGIN_VALIDATE_CODE = "login_validate_code";
/**
* 登录验证码图片
*/
@RequestMapping(value = {"/loginValidateCode"})
public void loginValidateCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
CommonUtil.validateCode(request,response,captchaProducer,LOGIN_VALIDATE_CODE);
}
/**
* 检查验证码是否正确
*/
@RequestMapping("/checkLoginValidateCode")
@ResponseBody
public HashMap checkLoginValidateCode(HttpServletRequest request, @RequestParam("validateCode")String validateCode) {
String loginValidateCode = request.getSession().getAttribute(LOGIN_VALIDATE_CODE).toString();
HashMap<String,Object> map = new HashMap<String,Object>();
if(loginValidateCode == null){
map.put("status",null);//验证码过期
}else if(loginValidateCode.equals(validateCode)){
map.put("status",true);//验证码正确
}else if(!loginValidateCode.equals(validateCode)){
map.put("status",false);//验证码不正确
}
map.put("code",200);
return map;
}
}
前端代码
到这里后端的部分已经完成了,大部分都是一样的,只需要轻微改动
2.5 登录界面
这里直接将我网站的登录界面直接贴出,不需要的代码可自行删除。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>会员中心-登录</title>
</head>
<body>
<table class="login_tab" width="270" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>验证码:</td>
<td><input type="text" id="validateCode" name="validateCode" value="" placeholder="请输入验证码"/></td><td> </td>
<td><img id="loginValidateCode" height="35" width="80" style="cursor: pointer;" src="/loginValidateCode" onclick="uploadLoginValidateCode();"></td>
</tr>
<tr>
<td></td>
<td>
<button class="log_b" type="submit">登 录</button>
</td>
</tr>
</table>
<script type="text/javascript" src="/js/jquery/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/js/kaptcha.js"></script>//导入kaptcha.js文件
<script type='text/javascript'></script>
</body>
</html>
2.6 编写js代码,新建kaptcha.js
$(function () {
$("#validateCode").keyup(function(){
checkLoginValidateCode($(this).val());
});
});
function uploadLoginValidateCode() {
//点击验证码刷新验证码
$("#loginValidateCode").attr("src","/loginValidateCode?random="+new Date().getMilliseconds());
}
function checkLoginValidateCode(validateCode) {
var error = $("#validateCode").parent().next();
if(validateCode != null && validateCode != ""){
$.ajax({
type: "POST",
async:false,
url: "/checkLoginValidateCode?validateCode="+validateCode,
success : function(json) {
if(json != null && json.code == 200 && json.status != null) {
if (json.status == true) {
error.html("恭喜你验证码,正确!!!");
} else if(json.status == false){
error.html("验证码错误,请重新输入");
}else{
error.html("验证码过期,请重新输入");
uploadLoginValidateCode();
}
}
return false;
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("服务器错误!状态码:"+XMLHttpRequest.status);
// 状态
console.log(XMLHttpRequest.readyState);
// 错误信息
console.log(textStatus);
return false;
}
});
}else{
error.html("请输入验证码!");
}
}
2.7效果图

Springboot实现验证码登录的更多相关文章
- SpringBoot + Spring Security 学习笔记(五)实现短信验证码+登录功能
在 Spring Security 中基于表单的认证模式,默认就是密码帐号登录认证,那么对于短信验证码+登录的方式,Spring Security 没有现成的接口可以使用,所以需要自己的封装一个类似的 ...
- SpringBoot 整合 Shiro 密码登录与邮件验证码登录(多 Realm 认证)
导入依赖(pom.xml) <!--整合Shiro安全框架--> <dependency> <groupId>org.apache.shiro</group ...
- springboot +spring security4 自定义手机号码+短信验证码登录
spring security 默认登录方式都是用户名+密码登录,项目中使用手机+ 短信验证码登录, 没办法,只能实现修改: 需要修改的地方: 1 .自定义 AuthenticationProvide ...
- Springboot 生成验证码
技术:springboot+kaptcha+session 概述 场景介绍 验证码,用于web网站.用户点击验证码图片后,生成验证码.提交后,用户输入验证码和Session验证码,进行校验. 详细 ...
- Spring Security实现短信验证码登录
Spring Security默认的一个实现是使用用户名密码登录,当初我们在开始做项目时,也是先使用这种登录方式,并没有多考虑其他的登录方式.而后面需求越来越多,我们需要支持短信验证码登录了,这时候再 ...
- requests库使用:通过cookie跳过验证码登录,并用Session跨请求保持cookie
拿我平时测试的一个系统为例,从UI层面来说必须先登录才可以进行后续操作,但是我在测试接口文档提供的接口时,发现并不需要登录,每个接口只要传参就可以正常返回.原因是我们这边专门弄了一个接口包来统一管理常 ...
- vue实现短信验证码登录
无论是移动端还是pc端登录或者注册界面都会见到手机验证码登录这个功能,输入手机号,得到验证码,最后先服务器发送请求,保存登录的信息,一个必不可少的功能 思路 1,先判断手机号和验证是否为空, 2,点击 ...
- Spring Security构建Rest服务-1203-Spring Security OAuth开发APP认证框架之短信验证码登录
浏览器模式下验证码存储策略 浏览器模式下,生成的短信验证码或者图形验证码是存在session里的,用户接收到验证码后携带过来做校验. APP模式下验证码存储策略 在app场景下里是没有cookie信息 ...
- Spring Security构建Rest服务-0702-短信验证码登录
先来看下 Spring Security密码登录大概流程,模拟这个流程,开发短信登录流程 1,密码登录请求发送给过滤器 UsernamePasswordAuthenticationFilter 2,过 ...
随机推荐
- [HNOI2010]弹飞绵羊 (平衡树,LCT动态树)
题面 题解 因为每个点都只能向后跳到一个唯一的点,但可能不止一个点能跳到后面的某个相同的点, 所以我们把它抽象成一个森林.(思考:为什么是森林而不是树?) 子节点可以跳到父节点,根节点再跳就跳飞了. ...
- 抛砖系列之git仓库拆分工具git-filter-repo
最近负责把团队内的git仓库做了一次分拆,解锁一个好用的工具git-filter-repo,给大伙抛砖一波,希望以后遇到类似场景时可以信手拈来. 背景 笔者团队目前是把业务相关的java项目都放到了一 ...
- 知乎问题之:.NET AOT编译后能替代C++吗?
标题上的Native库是指:Native分为静态库( 作者:nscript链接:https://www.zhihu.com/question/536903224/answer/2522626086 ( ...
- Git Rebase-提交整洁之道
git rebase git rebase是一个非常有用的命令,但知道和用的人非常少,今天介绍一下其作用 git rebase -i 作用:常用来合并多个相同目的的提交. 交互式有下面几个命令,常用命 ...
- C# 常见面试问题
C# 常见面试问题 EntityFramework 数据持久化 C#中的委托是什么?事件是不是一种委托? C#中的委托是一种引用类型,表示具有相同方法签名的方法的引用.类似于函数指针,也就是说它们是指 ...
- 【前端】在浏览器控制台,直接发Ajax请求
我们在日常的开发的过程中,经常需要前端测试发送请求测试一些数据.但是由于一些session,cookie的存在,我们无法在postman上创建一些会话.那么这样,我们就可以在浏览器上直接发送Ajax请 ...
- python基础__十大经典排序算法
用Python实现十大经典排序算法! 排序算法是<数据结构与算法>中最基本的算法之一.排序算法可以分为内部排序和外部排序,内部排序是数据记录在内存中进行排序,而外部排序是因排序的数据很大, ...
- 2.2 virtualenv 虚拟环境
有的时候因为各种原因,在操作系统下,我们会安装很多版本的Python解释器.同样,我们也有可能因为各种原因,需要不同版本的模块,比如Django1.8,Django1.11.再加上pip工具管理器的版 ...
- 关于Elasticsearch使用java的说明
从Elastic 7.0开始,我们可以不安装JAVA.安装包包含一个相匹配的JAVA版本在里面. Elasticsearch包含来自JDK维护者(GPLv2 + CE)的捆绑版OpenJDK. 要使用 ...
- 苹果手机安装郑好办手机app后给绿城通公交卡充值的步骤
1.苹果手机,需要带有NFC功能 苹果XS手机该功能默认是开启的,不用额外的其他操作 苹果11该功能需要设置开启才行.步骤:设置--通用--NFC,然后开启 2,公交卡 如下这种的公交卡可以充值: 如 ...