kaptcha验证码实现,配合spring boot使用
一、kaptcha介绍
Kaptcha是谷歌放在github上的一个验证码jar包,我们可以简单配置属性实现验证码的验证功能。
kaptcha参数设置如下所示:
Constant 描述 默认值
kaptcha.border 图片边框,合法值:yes , no yes
kaptcha.border.color 边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue. black
kaptcha.border.thickness 边框厚度,合法值:>0 1
kaptcha.image.width 图片宽 200
kaptcha.image.height 图片高 50
kaptcha.producer.impl 图片实现类 com.google.code.kaptcha.impl.DefaultKaptcha
kaptcha.textproducer.impl 文本实现类 com.google.code.kaptcha.text.impl.DefaultTextCreator
kaptcha.textproducer.char.string 文本集合,验证码值从此集合中获取 abcde2345678gfynmnpwx
kaptcha.textproducer.char.length 验证码长度 5
kaptcha.textproducer.font.names 字体 Arial, Courier
kaptcha.textproducer.font.size 字体大小 40px.
kaptcha.textproducer.font.color 字体颜色,合法值: r,g,b 或者 white,black,blue. black
kaptcha.textproducer.char.space 文字间隔 2
kaptcha.noise.impl 干扰实现类 com.google.code.kaptcha.impl.DefaultNoise
kaptcha.noise.color 干扰颜色,合法值: r,g,b 或者 white,black,blue. black
kaptcha.obscurificator.impl 图片样式: 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影
com.google.code.kaptcha.impl.ShadowGimpy com.google.code.kaptcha.impl.WaterRipple
kaptcha.background.impl 背景实现类 com.google.code.kaptcha.impl.DefaultBackground
kaptcha.background.clear.from 背景颜色渐变,开始颜色 light grey
kaptcha.background.clear.to 背景颜色渐变,结束颜色 white
kaptcha.word.impl 文字渲染器 com.google.code.kaptcha.text.impl.DefaultWordRenderer
kaptcha.session.key session key KAPTCHA_SESSION_KEY
kaptcha.session.date session date KAPTCHA_SESSION_DATE
二、实现
1、引入maven依赖
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2、编写配置类
package com.example.demo.config; 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 zsh
* @company wlgzs
* @create 2019-03-10 9:37
* @Describe CaptchaConfig配置类
*/
@Configuration
public class CaptchaConfig { @Bean(name = "captchaProducer")
public DefaultKaptcha getKaptchaBean(){
DefaultKaptcha defaultKaptcha=new DefaultKaptcha();
Properties properties=new Properties();
properties.setProperty("kaptcha.border", "yes");
properties.setProperty("kaptcha.border.color", "105,179,90");
properties.setProperty("kaptcha.textproducer.font.color", "blue");
properties.setProperty("kaptcha.image.width", "125");
properties.setProperty("kaptcha.image.height", "45");
properties.setProperty("kaptcha.session.key", "code");
properties.setProperty("kaptcha.textproducer.char.length", "5");
properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
Config config=new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
} }
3、编写controller类
package com.example.demo; import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream; /**
* @author zsh
* @company wlgzs
* @create 2019-03-10 9:41
* @Describe Captcha测试controller
*/
@Controller
public class CaptchaController { @Autowired
DefaultKaptcha defaultKaptcha; /**
* 显示验证码
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/defaultKaptcha")
public void defaultKaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
byte[] captchaChallengeAsJpeg = null;
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
//生产验证码字符串并保存到session中
String createText = defaultKaptcha.createText();
request.getSession().setAttribute("verifyCode", createText);
//使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
BufferedImage challenge = defaultKaptcha.createImage(createText);
ImageIO.write(challenge, "jpg", jpegOutputStream);
} catch (IllegalArgumentException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
//定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
ServletOutputStream responseOutputStream =
response.getOutputStream();
responseOutputStream.write(captchaChallengeAsJpeg);
responseOutputStream.flush();
responseOutputStream.close();
} @PostMapping("/verifyCode")
public String imgverifyControllerDefaultKaptcha(Model model, HttpSession session, String verifyCode) {
String captchaId = (String) session.getAttribute("verifyCode");
System.out.println("验证码是:" + captchaId);
System.out.println("用户输入的是:" + verifyCode);
if (!captchaId.equals(verifyCode)) {
System.out.println("输入错误");
model.addAttribute("info", "错误的验证码");
} else {
System.out.println("输入正确");
model.addAttribute("info", "正确");
}
return "/index";
} @GetMapping("/")
public ModelAndView test() {
return new ModelAndView("index");
} }
4、编写测试页面
-------------Kaptcha验证码
<h1 th:text="${info}"/>
<div>
<img alt="验证码" onclick="this.src='/defaultKaptcha?d='+new Date()*1" src="/defaultKaptcha"/>
</div>
<form action="/verifyCode" method="post">
<input type="text" name="verifyCode"/>
<input type="submit" value="提交"/>
</form>
5、效果
kaptcha验证码实现,配合spring boot使用的更多相关文章
- Spring Boot快速集成kaptcha生成验证码
Kaptcha是一个非常实用的验证码生成工具,可以通过配置生成多样化的验证码,以图片的形式显示,从而无法进行复制粘贴:下面将详细介绍下Spring Boot快速集成kaptcha生成验证码的过程. 本 ...
- 在Spring Boot启动后执行指定代码
在开发时有时候需要在整个应用开始运行时执行一些特定代码,比如初始化环境,准备测试数据等等. 在Spring中可以通过ApplicationListener来实现相关的功能,不过在配合Spring Bo ...
- Spring Boot 2.x(十三):你不知道的PageHelper
PageHelper 说起PageHelper,使用过Mybatis的朋友可能不是很陌生,作为一款国人开发的分页插件,它基本上满足了我们的日常需求.但是,我想去官方文档看看这个东西配合Spring B ...
- 精通Spring Boot
原 精通Spring Boot—— 第二十一篇:Spring Social OAuth 登录简介 1.什么是OAuth OAuth官网介绍是这样的: An open protocol to allow ...
- spring boot:spring security给用户登录增加自动登录及图形验证码功能(spring boot 2.3.1)
一,图形验证码的用途? 1,什么是图形验证码? 验证码(CAPTCHA)是"Completely Automated Public Turing test to tell Computers ...
- spring boot:用redis+lua限制短信验证码的发送频率(spring boot 2.3.2)
一,为什么要限制短信验证码的发送频率? 1,短信验证码每条短信都有成本制约, 肯定不能被刷接口的乱发 而且接口被刷会影响到用户的体验, 影响服务端的正常访问, 所以既使有图形验证码等的保护, 我们仍然 ...
- Spring boot配合Spring session(redis)遇到的错误
背景:本MUEAS项目,一开始的时候,是没有引入redis的,考虑到后期性能的问题而引入.之前没有引用redis的时候,用户登录是正常的.但是,在加入redis支持后,登录就出错!错误如下: . __ ...
- Spring Boot 创建定时任务(配合数据库动态执行)
序言:创建定时任务非常简单,主要有两种创建方式:一.基于注解(@Scheduled) 二.基于接口(SchedulingConfigurer). 前者相信大家都很熟悉,但是实际使用中我们往往想从数据库 ...
- (转)Spring Boot (十四): Spring Boot 整合 Shiro-登录认证和权限管理
http://www.ityouknow.com/springboot/2017/06/26/spring-boot-shiro.html 这篇文章我们来学习如何使用 Spring Boot 集成 A ...
随机推荐
- FlexViewer之整体框架解析
参考:https://www.cnblogs.com/naaoveGIS/p/3915912.html GIS之家:https://xiaozhuanlan.com/gishome 小专栏:https ...
- MyBatis基础入门《十 一》修改数据
MyBatis基础入门<十 一>修改数据 实体类: 接口类: xml文件: 测试类: 测试结果: 数据库: 如有问题,欢迎纠正!!! 如有转载,请标明源处:https://www.cnbl ...
- python时间和日期
一.time 和 calendar 模块可以用于格式化日期和时间 import time; # 引入time模块 ticks = time.time() print "当前时间戳为:&quo ...
- 有复选框情况下,sql拼写技巧
复选框选中只取合格的数据,没有选中取所有的数据. string filterOk = (ckbOnlyOk.Checked ? " and (jyjg='合格') " : &quo ...
- python subprocess中ssh命令的特殊性
今天尝试使用python 的 subprocess 模块 使用类似如下语句: p=subprocess.Popen(['ssh','root@localhost'],stdout=subprocess ...
- vss使用笔记
一.四大代码/文档管理软件 (1) git:具有PR(push request)特性,推送请求.需要负责人审核后才能推送.另外,在推送过程中,git会预编译(合并),分布式代码管理(客户端本地 ...
- RRDtool 安装和使用
一.RRDtool 的功能及使用介绍 定义:RRDtool(Round Robin Database Tool)是一个用来处理定量数据的开源高性能数据库. 1.RRDtool 的特性 由于 RRDto ...
- Python scrapy - Login Authenication Issue
https://stackoverflow.com/questions/37841409/python-scrapy-login-authenication-issue from scrapy.cra ...
- 多线程:Operation(二)
1. Operation 设置依赖关系 先看看如何设置operation的依赖关系. 啥叫依赖关系?有啥用啊?打个比方咱们要做一个听音乐的付费App项目,需要经过登陆.付费.下载.播放四个步骤.其实一 ...
- python pymssql 连接数据库
1)写在前面 远程连接数据库的时候,端口前面都是用的逗号, 因为惯性思维, 就傻傻的把 ip+,+端口 赋值给server了,然后一直报错, pymssql.InterfaceError: Co ...