springboot集成kaptcha验证码

准备工作:

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

     2.导入kaptcha的maven:

  1. <!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->  
  2. <dependency>  
  3.     <groupId>com.github.penggle</groupId>  
  4.     <artifactId>kaptcha</artifactId>  
  5.     <version>2.3.2</version>  
  6. </dependency>  

有两种方式在springboot中使用kaptcha

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

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


方法

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

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">  
  5.     <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">  
  6.         <property name="config">  
  7.             <bean class="com.google.code.kaptcha.util.Config">  
  8.                 <constructor-arg type="java.util.Properties">  
  9.                     <props>  
  10.                         <prop key = "kaptcha.border ">yes</prop>  
  11.                             <prop key="kaptcha.border.color">105,179,90</prop>  
  12.                             <prop key="kaptcha.textproducer.font.color">blue</prop>  
  13.                             <prop key="kaptcha.image.width">100</prop>  
  14.                             <prop key="kaptcha.image.height">50</prop>  
  15.                             <prop key="kaptcha.textproducer.font.size">27</prop>  
  16.                             <prop key="kaptcha.session.key">code</prop>  
  17.                             <prop key="kaptcha.textproducer.char.length">4</prop>  
  18.                             <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>  
  19.                             <prop key="kaptcha.textproducer.char.string">0123456789ABCEFGHIJKLMNOPQRSTUVWXYZ</prop>  
  20.                             <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.WaterRipple</prop>  
  21.                             <prop key="kaptcha.noise.color">black</prop>  
  22.                             <prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.DefaultNoise</prop>  
  23.                             <prop key="kaptcha.background.clear.from">185,56,213</prop>  
  24.                             <prop key="kaptcha.background.clear.to">white</prop>  
  25.                             <prop key="kaptcha.textproducer.char.space">3</prop>  
  26.                     </props>  
  27.                 </constructor-arg>  
  28.             </bean>  
  29.         </property>  
  30.     </bean>  
  31.   
  32. </beans>  

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

  1. @SpringBootApplication  
  2. @ImportResource(locations={"classpath:mykaptcha.xml"})  
  3. public class Application {  
  4.   
  5.     public static void main(String[] args) {  
  6.         SpringApplication.run(Application.class, args);  
  7.     }  
  8. }  


在controller中使用:

  1. @Autowired  
  2. DefaultKaptcha defaultKaptcha; 
  3. ......

  1. @RequestMapping("/defaultKaptcha")  
  2.     public void defaultKaptcha(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception{  
  3.             byte[] captchaChallengeAsJpeg = null;    
  4.              ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();    
  5.              try {    
  6.              //生产验证码字符串并保存到session中  
  7.              String createText = defaultKaptcha.createText();  
  8.              httpServletRequest.getSession().setAttribute("vrifyCode", createText);  
  9.              //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中  
  10.              BufferedImage challenge = defaultKaptcha.createImage(createText);  
  11.              ImageIO.write(challenge, "jpg", jpegOutputStream);  
  12.              } catch (IllegalArgumentException e) {    
  13.                  httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);    
  14.                  return;    
  15.              }   
  16.          
  17.              //定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组  
  18.              captchaChallengeAsJpeg = jpegOutputStream.toByteArray();    
  19.              httpServletResponse.setHeader("Cache-Control""no-store");    
  20.              httpServletResponse.setHeader("Pragma""no-cache");    
  21.              httpServletResponse.setDateHeader("Expires"0);    
  22.              httpServletResponse.setContentType("image/jpeg");    
  23.              ServletOutputStream responseOutputStream =    
  24.                      httpServletResponse.getOutputStream();    
  25.              responseOutputStream.write(captchaChallengeAsJpeg);    
  26.              responseOutputStream.flush();    
  27.              responseOutputStream.close();    
  28.     }  

验证的方法:

  1. @RequestMapping("/imgvrifyControllerDefaultKaptcha")  
  2. public ModelAndView imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse){  
  3.     ModelAndView andView = new ModelAndView();  
  4.      String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifyCode");    
  5.      String parameter = httpServletRequest.getParameter("vrifyCode");  
  6.      System.out.println("Session  vrifyCode "+captchaId+" form vrifyCode "+parameter);  
  7.        
  8.     if (!captchaId.equals(parameter)) {  
  9.         andView.addObject("info""错误的验证码");  
  10.         andView.setViewName("index");  
  11.     } else {  
  12.         andView.addObject("info""登录成功");  
  13.         andView.setViewName("succeed");  
  14.           
  15.     }  
  16.     return andView;  
  17. }  
模板html:

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head lang="en">  
  4.     <meta charset="UTF-8" />  
  5.     <title>hello</title>  
  6. </head>  
  7. <body>  
  8.     <h1 th:text="${info}" />  
  9.     <div>  
  10.         <!-- <img alt="这是图片" src="/img/001.png"/> -->  
  11.         <img alt="验证码" onclick = "this.src='/defaultKaptcha?d='+new Date()*1" src="/defaultKaptcha" />  
  12.     </div>  
  13.     <form action="imgvrifyControllerDefaultKaptcha">  
  14.         <input type="text" name="vrifyCode" />  
  15.         <input type="submit" value="提交"></input>  
  16.     </form>  
  17. </body>  
  18. </html>  
启动并访问,进行验证。


方法二:

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

  1. import java.util.Properties;  
  2.   
  3. import org.springframework.context.annotation.Bean;  
  4. import org.springframework.stereotype.Component;  
  5.   
  6. import com.google.code.kaptcha.impl.DefaultKaptcha;  
  7. import com.google.code.kaptcha.util.Config;  
  8.   
  9. @Component  
  10. public class KaptchaConfig {  
  11.     @Bean  
  12.     public DefaultKaptcha getDefaultKaptcha(){  
  13.         com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();  
  14.         Properties properties = new Properties();  
  15.         properties.setProperty("kaptcha.border""yes");  
  16.         properties.setProperty("kaptcha.border.color""105,179,90");  
  17.         properties.setProperty("kaptcha.textproducer.font.color""blue");  
  18.         properties.setProperty("kaptcha.image.width""110");  
  19.         properties.setProperty("kaptcha.image.height""40");  
  20.         properties.setProperty("kaptcha.textproducer.font.size""30");  
  21.         properties.setProperty("kaptcha.session.key""code");  
  22.         properties.setProperty("kaptcha.textproducer.char.length""4");  
  23.         properties.setProperty("kaptcha.textproducer.font.names""宋体,楷体,微软雅黑");  
  24.         Config config = new Config(properties);  
  25.         defaultKaptcha.setConfig(config);  
  26.           
  27.         return defaultKaptcha;  
  28.     }  
  29. }  

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



温馨提示:也有使用jcaptcha的,但是它们最好不要在一个工程中使用,因为用到了相同的类,可能导致异常。



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值