技术:springboot+kaptcha+session
 

概述

场景介绍 验证码,用于web网站。用户点击验证码图片后,生成验证码。提交后,用户输入验证码和Session验证码,进行校验。

详细

一、目录结构

二、功能讲解

(1)验证码配置文件

打开KaptchaConfig.java

@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", "5");
//干扰实现类
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;
} }

详细配置说明:https://blog.csdn.net/elephantboy/article/details/52795309

(2)生成验证码方法

打开CommonUtil.java,这是一个公共方法

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();
}
} }

(3)验证码控制类

打开MainController.java

@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;
}
}

(4)前端页面

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>SpringBoot 生成验证码</title>
<script type="text/javascript" src="/js/jquery/jquery-3.3.1.min.js"></script>
<script type='text/javascript'> $(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("请输入验证码!");
}
} </script>
</head>
<body>
验证码: <img id="loginValidateCode" height="40" width="150" style="cursor: pointer;" src="/loginValidateCode" onclick="uploadLoginValidateCode();"> <p>
你输入的内容:<input type="text" id="validateCode" name="validateCode" />
</p>
<p style="color: red"></p> </body>
</html>

三、运行

访问链接:http://127.0.0.1:8080

吐槽环节:百度的搜java 验证码,太坑爹了,各种各样复杂,非常不通用,还有一些不能运行的。忍不了忍不了,自己整合一个,最后找到google kaptcha 工具 vary good !!!

谢谢大家观看~

注:本文著作权归作者,由demo大师发表,拒绝转载,转载需要作者授权

Springboot 生成验证码的更多相关文章

  1. SpringBoot开发九-生成验证码

    需求介绍-生成验证码 先生成随机字符串然后利用Kaptcha API生成验证图片 代码实现 先在pom.xml引入 <dependency> <groupId>com.gith ...

  2. Spring Boot快速集成kaptcha生成验证码

    Kaptcha是一个非常实用的验证码生成工具,可以通过配置生成多样化的验证码,以图片的形式显示,从而无法进行复制粘贴:下面将详细介绍下Spring Boot快速集成kaptcha生成验证码的过程. 本 ...

  3. JAVA整合kaptcha生成验证码 (字母验证码和算术验证码)

    引入maven <!--图片验证码--> <dependency> <groupId>com.github.penggle</groupId> < ...

  4. Springboot实现验证码登录

    Springboot实现验证码登录 1.背景 本人近期正在完成毕业设计(旅游信息管理系统)的制作,采用的SpringBoot+Thymeleaf的模式.在登录网站时想要添加验证码验证,通过网上查找资料 ...

  5. 动态生成验证码———MVC版

    上面有篇博客也是写的验证码,但那个是适用于asp.net网站的. 今天想在MVC中实现验证码功能,弄了好久,最后还是看博友文章解决的,感谢那位博友. 首先引入生成验证码帮助类. ValidateCod ...

  6. laravel 生成验证码的方法

    在Laravel中有很多图片验证码的库可以使用,本篇介绍其中之一:gregwar/captcha,这个库比较简单,在Laravel中比较常用.下面我们就来介绍下使用细节: 首先, composer.j ...

  7. java web学习总结(九) -------------------通过Servlet生成验证码图片

    一.BufferedImage类介绍 生成验证码图片主要用到了一个BufferedImage类,如下:

  8. android 生成验证码图片

    (转自:http://blog.csdn.net/onlyonecoder/article/details/8231373) package com.nobeg.util; import java.u ...

  9. PHP 动态生成验证码

    ……机器人会在网站中搜寻允许他们插入广告的输入表单,在虚拟世界没有什么能阻挡它们胡作非为.这些机器人效率极高,完全不关心所攻击的表单的本来用途.它们唯一的目标就是用它们的垃圾广告覆盖你的内容,残忍地为 ...

随机推荐

  1. css上传图片中等待不可点击效果

    <!DOCTYPE html> <html> <head> <title>上传中</title> <style type=" ...

  2. 最短路(bellman)-hdu1217

    Dijkstra算法是处理单源最短路径的有效算法,但它局限于边的权值非负的情况,若图中出现权值为负的边,Dijkstra算法就会失效,求出的最短路径就可能是错的. 这时候,就需要使用其他的算法来求解最 ...

  3. JavaEE 之 Spring(二)

    1.AOP(面向切面编程) a.定义:AOP将分散在系统中的功能块放到一个地方——切面 b.重要术语: ①切面(Aspect):就是你要实现的交叉功能---共通业务处理可以被切入到多个目标对象.并且多 ...

  4. DT:DT实现根据乳腺肿瘤特征向量高精度预测肿瘤的是恶性还是良性—Jason niu

    %DT:DT实现根据乳腺肿瘤特征向量高精度预测肿瘤的是恶性还是良性 load data.mat a = randperm(569); Train = data(a(1:500),:); Test = ...

  5. ZOJ 1610 Count the Colors 【线段树】

    <题目链接> 题目大意: 在[0,8000]这个区间内,不断进行一些操作,将其中的一些区间染成特定颜色,如果区间重复的话,后面染的色块会覆盖前面染的色块,问最终[0,8000]这个区间内每 ...

  6. [C程序设计基础]快速排序

    //从大到小排序 ///三个参数 a要排序的 数组, l扫左边的 r扫右边 void quickSort(int a[],int l, int r){ /// 左边要小于 右边才有意义 if (l & ...

  7. VMware5.5-vCenter Converter(转换)

    vCenter Converter 已知问题 出现:指定的参数不正确: "info.owner" 操作时一定是管理员,而不是管理员组的成员.或者: 如果 Converter Sta ...

  8. BZOJ.4399.魔法少女LJJ(线段树合并)

    BZOJ 注意\(c\leq7\)→_→ 然后就是裸的权值线段树+线段树合并了. 对于取\(\max/\min\)操作可以直接区间修改清空超出范围的值,然后更新到对应位置上就行了(比如对\(v\)取\ ...

  9. 洛谷.3369.[模板]普通平衡树(fhq Treap)

    题目链接 第一次(2017.12.24): #include<cstdio> #include<cctype> #include<algorithm> //#def ...

  10. [ONTAK2015]OR-XOR

    [ONTAK2015]OR-XOR 题目大意: 一个长度为\(n(n\le5\times10^5)\)的序列\(A(0\le A_i\le10^{18})\),将其分为恰好\(m\)个连续段,设每一段 ...