验证码(CAPTCHA)是“Completely Automated Public Turing test to tell Computers and Humans Apart”(全自动区分计算机和人类的图灵测试)的缩写,是一种区分用户是计算机还是人的公共全自动程序。可以防止:恶意破解密码、刷票、论坛灌水,有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试,实际上用验证码是现在很多网站通行的方式,我们利用比较简易的方式实现了这个功能。今天给大家介绍一下kaptcha的和springboot一起使用的简单例子。

准备工作

1.首要要有一个可以运行的springboot的项目并可以正常运行

2.导入kaptcha依赖

<!--验证码-->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>

开始试验

我们有两种方式在springboot中使用kaptcha

1.使用.xml的配置方式配置生成kaptcha的bean对象,在启动类上@ImportResource这个xml文件;在controller中注入其对象并使用

2.是把kaptcha作为工程的一个类,加上@component注解在返回kaptcha的方法中加上@Bean注解,再在controller中注入其对象。

第一种方法

在resources中创建一个kaptchaConfig.xml文件 如:

kaptchaConfig.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
<property name="config">
<bean class="com.google.code.kaptcha.util.Config">
<constructor-arg type="java.util.Properties">
<props>
<!--是否使用边框-->
<prop key = "kaptcha.border ">yes</prop>
<!--边框颜色-->
<prop key="kaptcha.border.color">105,179,90</prop>
<!--验证码字体颜色-->
<prop key="kaptcha.textproducer.font.color">blue</prop>
<!--验证码图片的宽度-->
<prop key="kaptcha.image.width">100</prop>
<!--验证码图片的高度-->
<prop key="kaptcha.image.height">50</prop>
<!--验证码字体的大小-->
<prop key="kaptcha.textproducer.font.size">27</prop>
<!--验证码保存在session的key-->
<prop key="kaptcha.session.key">code</prop>
<!--验证码输出的字符长度-->
<prop key="kaptcha.textproducer.char.length">4</prop>
<!--验证码的字体设置-->
<prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>
<!--验证码的取值范围-->
<prop key="kaptcha.textproducer.char.string">0123456789ABCEFGHIJKLMNOPQRSTUVWXYZ</prop>
<!--图片的样式-->
<prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.WaterRipple</prop>
<!--干扰颜色,合法值: r,g,b 或者 white,black,blue.-->
<prop key="kaptcha.noise.color">black</prop>
<!--干扰实现类-->
<prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.DefaultNoise</prop>
<!--背景颜色渐变,开始颜色-->
<prop key="kaptcha.background.clear.from">185,56,213</prop>
<!--背景颜色渐变,结束颜色-->
<prop key="kaptcha.background.clear.to">white</prop>
<!--文字间隔-->
<prop key="kaptcha.textproducer.char.space">3</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>
</beans>

在springboot启动类上引入这个文件

@SpringBootApplication
@ImportResource(locations={"classpath:kaptchaConfig.xml"})
public class CodeDemoApplication { public static void main(String[] args) {
SpringApplication.run(CodeDemoApplication.class, args);
}
}

在controller中注入DefaultKaptcha

@Autowired
DefaultKaptcha defaultKaptcha;

在controller中编写获取验证码图片的方法

//获取验证码
@RequestMapping("/getCode")
public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
byte[] captchaChallengeAsJpeg = null;
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
//生产验证码字符串并保存到session中
String createText = defaultKaptcha.createText();
httpServletRequest.getSession().setAttribute("vrifyCode", createText);
//使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
BufferedImage challenge = defaultKaptcha.createImage(createText);
ImageIO.write(challenge, "jpg", jpegOutputStream);
} catch (IllegalArgumentException e) {
httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
//定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
httpServletResponse.setHeader("Cache-Control", "no-store");
httpServletResponse.setHeader("Pragma", "no-cache");
httpServletResponse.setDateHeader("Expires", 0);
httpServletResponse.setContentType("image/jpeg");
ServletOutputStream responseOutputStream =
httpServletResponse.getOutputStream();
responseOutputStream.write(captchaChallengeAsJpeg);
responseOutputStream.flush();
responseOutputStream.close();
}

在controller中编写验证的方法

//验证码验证
@RequestMapping("/checkCode")
@ResponseBody
public boolean imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifyCode");
String parameter = httpServletRequest.getParameter("code");
log.info("Session vrifyCode ---->"+captchaId+"---- form code --->"+parameter);
if (!captchaId.equals(parameter)) {
log.info("错误的验证码");
return false;
} else {
return true;
}
}

模板页面register.html

......
<div class="form-group">
<label class="col-md-2 col-md-offset-2 control-label">验证码</label>
<div class="col-md-3">
<div class="row_bj" style="width:100%;">
<input type="text" class="form-control" id="code" name="code" required placeholder="请输入验证码">
<img alt="验证码" onclick = "this.src='/getCode?d='+new Date()*1" src="/getCode" style="margin-left:20px;"/>
</div>
<label class="control-label text-danger" id="code2">(验证码错误)</label>
</div>
</div>
......

启动访问

控制台日志结果:

第二种方法:这种方法把.xml文件换成使用代码来配置:

KaptchaConfig配置类:

@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", "105,179,90");
properties.setProperty("kaptcha.textproducer.font.color", "red");
properties.setProperty("kaptcha.image.width", "110");
properties.setProperty("kaptcha.image.height", "40");
properties.setProperty("kaptcha.textproducer.font.size", "40");
properties.setProperty("kaptcha.session.key", "code");
properties.setProperty("kaptcha.textproducer.char.length", "4");
properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}

注意要去掉启动类中引入的.xml文件,不然会有两个相同的对象,而你没有指明要注入哪一个的话启动会失败。

补充:对于kaptcha的配置属性可以百度找一找。

springboot 集成kaptcha验证码Demo的更多相关文章

  1. springboot集成kaptcha验证码

    在pom.xml引入依赖 <!-- 验证码 --> <!-- https://mvnrepository.com/artifact/com.github.penggle/kaptch ...

  2. Springboot整合kaptcha验证码

    01.通过配置类来配置kaptcha 01-01.添加kaptcha的依赖: <!-- kaptcha验证码 --> <dependency> <groupId>c ...

  3. 关于SpringBoot集成JDBCTemplate的RowMapper问题

    JdbcTemplate 是Spring提供的一套JDBC模板框架,利用AOP 技术来解决直接使用JDBC时大量重复代码的问题.JdbcTemplate虽然没有MyBatis 那么灵活,但是直接使用J ...

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

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

  5. springboot集成mybatis(二)

    上篇文章<springboot集成mybatis(一)>介绍了SpringBoot集成MyBatis注解版.本文还是使用上篇中的案例,咱们换个姿势来一遍^_^ 二.MyBatis配置版(X ...

  6. springboot集成mybatis(一)

    MyBatis简介 MyBatis本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation迁移到了google code,并且改名为MyB ...

  7. 基于Springboot集成security、oauth2实现认证鉴权、资源管理

    1.Oauth2简介 OAuth(开放授权)是一个开放标准,允许用户授权第三方移动应用访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方移动应用或分享他们数据的所有内容,OAu ...

  8. springboot集成elasticsearch

    在基础阶段学习ES一般是首先是 安装ES后借助 Kibana 来进行CURD 了解ES的使用: 在进阶阶段可以需要学习ES的底层原理,如何通过Version来实现乐观锁保证ES不出问题等核心原理: 第 ...

  9. Springboot集成Spring Batch

    Spring官网 (https://spring.io/projects/spring-batch#overview)对Spring  Batch的解释: 一个轻量级的.全面的批处理框架,用于开发对企 ...

随机推荐

  1. ES6新增的math,Number方法

    ES6新增的math,Number方法,下面总结了一些我觉得有用的 Nunber.isInteger()判断是否为整数,需要注意的是1,和1.0都会被认为是整数 console.log(Number. ...

  2. ArcGIS Enterprise 10.5.1 静默安装部署记录(Centos 7.2 minimal)- 4、安装 ArcGIS for Server

    安装ArcGIS for Server 解压server安装包,tar -xzvf ArcGIS_Server_Linux_1051_156429.tar.gz 切换到arcgis账户静默安装serv ...

  3. Filter学习总结,顺便提及点servlet3.0异步filter和异步监听

      Filter介绍:     Filter在项目中经常可以用到,通常配置在web.xml中.是服务器端的一个组件,对于用户的请求和响应数据进行过滤操作,控制是否让用户访问到对应的web资源.常用于编 ...

  4. C#设计模式之代理模式(四)

    15.7 代理模式效果与适用场景 代理模式是常用的结构型设计模式之一,它为对象的间接访问提供了一个解决方案,可以对对象的访问进行控制.代理模式类型较多,其中远程代理.虚拟代理.保护代理等在软件开发中应 ...

  5. SpringBoot热部署插件

    1.配置在 maven工程中的pom.xml文件中 2.SpringBoot框架中提供的一个热部署插件,利用该热部署插件,我们可以在修改代码后不用重启应用,大大提高开发效率:

  6. ORACLE_LPAD_FUNCTION

    Oracle / PLSQL: LPAD Function This Oracle tutorial explains how to use the Oracle/PLSQL LPAD functio ...

  7. ORACLE_PROCEDURE_DROPTABLE

    WEBSITE:https://stackoverflow.com/questions/14564641/drop-a-table-in-a-procedure Qusetion:Hou to use ...

  8. ZOJ 2386 容斥原理

    题意:给出n个数,和m(1<=m<=200 000 000),求1~M中能被这n个数其中任意一个数整除的个数: 分析:n范围很小,可以枚举选择被哪些数整除,被奇数个整数整除加m/这个n个数 ...

  9. HDU 5258 数长方形【离散化+暴力】

    任意门:http://acm.hdu.edu.cn/showproblem.php?pid=5258 数长方形 Time Limit: 2000/1000 MS (Java/Others)    Me ...

  10. C# 利用HttpWebRequest进行HTTPS的post请求的示例

    最近一个推送信息的目标接口从http格式换成https格式,原来的请求无法正常发送,所以修改了发送请求的方法.标红的代码是新加了,改了之后就可以正常访问(不检测证书的) public static s ...