SpringBoot 集成Kaptcha实现验证码功能实例详解

发布时间 - 2026-01-11 02:50:05    点击率:

在一个web应用中验证码是一个常见的元素。不管是防止机器人还是爬虫都有一定的作用,我们是自己编写生产验证码的工具类,也可以使用一些比较方便的验证码工具。在网上收集一些资料之后,今天给大家介绍一下kaptcha的和springboot一起使用的简单例子。

准备工作:

1.你要有一个springboot的hello world的工程,并能正常运行。

2.导入kaptcha的maven:

<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha --> 
<dependency> 
 <groupId>com.github.penggle</groupId> 
 <artifactId>kaptcha</artifactId> 
 <version>2.3.2</version> 
</dependency> 

开始实验:

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

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

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

第一种方法:

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

mykaptcha.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> 
       <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> 
       <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:mykaptcha.xml"}) 
public class Application { 
 public static void main(String[] args) { 
  SpringApplication.run(Application.class, args); 
 } 
} 

在controller中使用:

@Autowired 
DefaultKaptcha defaultKaptcha; 
...... 
@RequestMapping("/defaultKaptcha") 
 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(); 
 } 

验证的方法:

@RequestMapping("/imgvrifyControllerDefaultKaptcha") 
public ModelAndView imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse){ 
 ModelAndView andView = new ModelAndView(); 
  String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifyCode"); 
  String parameter = httpServletRequest.getParameter("vrifyCode"); 
  System.out.println("Session vrifyCode "+captchaId+" form vrifyCode "+parameter); 
  
 if (!captchaId.equals(parameter)) { 
  andView.addObject("info", "错误的验证码"); 
  andView.setViewName("index"); 
 } else { 
  andView.addObject("info", "登录成功"); 
  andView.setViewName("succeed"); 
   
 } 
 return andView; 
} 

模板html:

<!DOCTYPE html> 
<html> 
<head lang="en"> 
 <meta charset="UTF-8" /> 
 <title>hello</title> 
</head> 
<body> 
 <h1 th:text="${info}" /> 
 <div> 
  <!-- <img alt="这是图片" src="/img/001.png"/> --> 
  <img alt="验证码" onclick = "this.src='/defaultKaptcha?d='+new Date()*1" src="/defaultKaptcha" /> 
 </div> 
 <form action="imgvrifyControllerDefaultKaptcha"> 
  <input type="text" name="vrifyCode" /> 
  <input type="submit" value="提交"></input> 
 </form> 
</body> 
</html> 

启动并访问:

提交:

第二中方发:

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

KaptchaConfig.Java:

import java.util.Properties; 
import org.springframework.context.annotation.Bean; 
import org.springframework.stereotype.Component; 
import com.google.code.kaptcha.impl.DefaultKaptcha; 
import com.google.code.kaptcha.util.Config; 
@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", "yes"); 
  properties.setProperty("kaptcha.border.color", "105,179,90"); 
  properties.setProperty("kaptcha.textproducer.font.color", "blue"); 
  properties.setProperty("kaptcha.image.width", "110"); 
  properties.setProperty("kaptcha.image.height", "40"); 
  properties.setProperty("kaptcha.textproducer.font.size", "30"); 
  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文件,不然会有两个相同的对象,而你没有指明要注入哪一个的话启动会失败。

启动并测试:

到这里就算成功了。(也有使用jcaptcha的,只是他们最好不要再一个工程中使用,使用到了相同的类,有时候会导致异常。)

补充:对于kaptcha的配置属性大家可以找找,根据属性就可以配置了。

总结

以上所述是小编给大家介绍的SpringBoot 集成Kaptcha实现验证码功能实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!


# spring  # boot  # kaptcha实现验证码  # SpringBoot实现短信验证码校验方法思路详解  # SpringBoot实现前端验证码图片生成和校验  # Springboot实现验证码登录  # SpringBoot发送邮箱验证码功能  # SpringBoot使用邮箱发送验证码实现注册功能  # springboot实现邮箱验证码功能  # SpringBoot发送邮件功能 验证码5分钟过期  # SpringBoot登录验证码实现过程详解  # SpringBoot后端验证码的实现示例  # 验证码  # 微软  # 给大家  # 小编  # 宋体  # 是一个  # 这是  # 也有  # 会有  # 你要  # 在此  # 要去  # 有一定  # 不要再  # 可以使用  # 种方法  # 有两种  # 而你  # 并能  # 准备工作 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: Laravel怎么发送邮件_Laravel Mail类SMTP配置教程  绝密ChatGPT指令:手把手教你生成HR无法拒绝的求职信  Laravel如何发送系统通知?(Notification渠道示例)  Laravel如何处理JSON字段的查询和更新_Laravel JSON列操作与查询技巧  北京企业网站设计制作公司,北京铁路集团官方网站?  Python面向对象测试方法_mock解析【教程】  Laravel如何实现密码重置功能_Laravel密码找回与重置流程  Linux虚拟化技术教程_KVMQEMU虚拟机安装与调优  javascript如何操作浏览器历史记录_怎样实现无刷新导航  Windows10如何更改计算机工作组_Win10系统属性修改Workgroup  Laravel如何自定义错误页面(404, 500)?(代码示例)  微信公众帐号开发教程之图文消息全攻略  Java Adapter 适配器模式(类适配器,对象适配器)优缺点对比  laravel怎么实现图片的压缩和裁剪_laravel图片压缩与裁剪方法  Laravel怎么创建自己的包(Package)_Laravel扩展包开发入门到发布  如何在IIS中配置站点IP、端口及主机头?  Laravel Session怎么存储_Laravel Session驱动配置详解  如何在阿里云虚拟主机上快速搭建个人网站?  网站广告牌制作方法,街上的广告牌,横幅,用PS还是其他软件做的?  如何在阿里云域名上完成建站全流程?  详解Android图表 MPAndroidChart折线图  猪八戒网站制作视频,开发一个猪八戒网站,大约需要多少?或者自己请程序员,需要什么程序员,多少程序员能完成?  如何彻底删除建站之星生成的Banner?  Laravel如何升级到最新版本?(升级指南和步骤)  PHP正则匹配日期和时间(时间戳转换)的实例代码  如何制作新型网站程序文件,新型止水鱼鳞网要拆除吗?  JS去除重复并统计数量的实现方法  佛山企业网站制作公司有哪些,沟通100网上服务官网?  如何用AWS免费套餐快速搭建高效网站?  iOS发送验证码倒计时应用  Python文件操作最佳实践_稳定性说明【指导】  canvas 画布在主流浏览器中的尺寸限制详细介绍  Win11怎么设置虚拟桌面 Win11新建多桌面切换操作【技巧】  如何在阿里云ECS服务器部署织梦CMS网站?  如何在 Python 中将列表项按字母顺序编号(a.、b.、c. …)  Laravel如何实现数据导出到PDF_Laravel使用snappy生成网页快照PDF【方案】  PHP 实现电台节目表的智能时间匹配与今日/明日轮播逻辑  javascript事件捕获机制【深入分析IE和DOM中的事件模型】  简历在线制作网站免费版,如何创建个人简历?  js代码实现下拉菜单【推荐】  如何快速查询网站的真实建站时间?  今日头条AI怎样推荐抢票工具_今日头条AI抢票工具推荐算法与筛选【技巧】  Laravel如何与Inertia.js和Vue/React构建现代单页应用  Laravel Facade的原理是什么_深入理解Laravel门面及其工作机制  深圳网站制作培训,深圳哪些招聘网站比较好?  深圳网站制作的公司有哪些,dido官方网站?  Laravel用户认证怎么做_Laravel Breeze脚手架快速实现登录注册功能  Laravel如何实现用户密码重置功能?(完整流程代码)  微信h5制作网站有哪些,免费微信H5页面制作工具?  车管所网站制作流程,交警当场开简易程序处罚决定书,在交警网站查询不到怎么办?