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

 更新时间:2017年08月17日 10:06:20   作者:也是右移  
在一个web应用中验证码是一个常见的元素。今天给大家介绍一下kaptcha的和springboot一起使用的简单例子。感兴趣的朋友参考下吧

在一个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实现验证码功能实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

相关文章

  • java类型生命周期的详细解析

    java类型生命周期的详细解析

    以下是对java中的类型生命周期进行了详细的分析介绍,需要的朋友可以过来参考下
    2013-08-08
  • JVM与操作系统之间的关系详解

    JVM与操作系统之间的关系详解

    JVM与操作系统之间是依赖与被依赖的关系,JVM依赖于操作系统提供的资源和服务,同时JVM也起到了抽象与隔离的作用,为Java程序提供了一个统一的、与平台无关的运行环境,提高了Java程序的安全性
    2025-03-03
  • SpringBoot返回结果统一处理实例详解

    SpringBoot返回结果统一处理实例详解

    这篇文章主要为大家介绍了SpringBoot返回结果统一处理实例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • JAVA实现SOCKET多客户端通信的案例

    JAVA实现SOCKET多客户端通信的案例

    这篇文章主要介绍了JAVA实现SOCKET多客户端通信的案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-12-12
  • Netty中序列化的作用及自定义协议详解

    Netty中序列化的作用及自定义协议详解

    这篇文章主要介绍了Netty中序列化的作用及自定义协议详解,Netty自身就支持很多种协议比如Http、Websocket等等,但如果用来作为自己的RPC框架通常会自定义协议,所以这也是本文的重点,需要的朋友可以参考下
    2023-12-12
  • 详解Springboot+React项目跨域访问问题

    详解Springboot+React项目跨域访问问题

    这篇文章主要介绍了详解Springboot+React项目跨域访问问题,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-11-11
  • Java使用DFA算法实现过滤多家公司自定义敏感字功能详解

    Java使用DFA算法实现过滤多家公司自定义敏感字功能详解

    这篇文章主要介绍了Java使用DFA算法实现过滤多家公司自定义敏感字功能,结合实例形式分析了DFA算法的实现原理及过滤敏感字的相关操作技巧,需要的朋友可以参考下
    2017-08-08
  • MyBatis在SQL语句中如何获取list的大小

    MyBatis在SQL语句中如何获取list的大小

    这篇文章主要介绍了MyBatis在SQL语句中如何获取list的大小问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • Java计算一个数加上100是完全平方数,加上168还是完全平方数

    Java计算一个数加上100是完全平方数,加上168还是完全平方数

    这篇文章主要介绍了Java计算一个数加上100是完全平方数,加上168还是完全平方数,需要的朋友可以参考下
    2017-02-02
  • 解析Spring Mvc Long类型精度丢失问题

    解析Spring Mvc Long类型精度丢失问题

    在平时开发过程中,经常会使用long类型作为id的类型,但是在使用过程中会导致long类型数据转换为number类型时的后两位变为0,今天小编给大家分享Spring Mvc Long类型精度丢失问题,需要的朋友参考下吧
    2021-06-06

最新评论