SpringBoot中集成kaptcha验证码

avatar 2018年05月04日16:55:13 6 4312 views
博主分享免费Java教学视频,B站账号:Java刘哥
在一个web应用中验证码是一个常见的元素。不管是防止机器人还是爬虫都有一定的作用,我们是自己编写生产验证码的工具类,也可以使用一些比较方便的验证码工具。 本文介绍 SpringBoot 和 Kaptcha 集成。  

一、pom.xml

  1. <dependency>
  2.     <groupId>com.github.penggle</groupId>
  3.     <artifactId>kaptcha</artifactId>
  4.     <version>2.3.2</version>
  5. </dependency>
 

二、配置验证码Kaptcha相关设置

  1. package com.liuyanzhao.forum.config;
  2. import com.google.code.kaptcha.impl.DefaultKaptcha;
  3. import com.google.code.kaptcha.util.Config;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import java.util.Properties;
  7. /**
  8.  * @author 言曌
  9.  * @date 2018/5/4 下午12:44
  10.  */
  11. @Configuration
  12. public class KaptchaConfig {
  13.     @Bean(name="captchaProducer")
  14.     public DefaultKaptcha getKaptchaBean(){
  15.         DefaultKaptcha defaultKaptcha=new DefaultKaptcha();
  16.         Properties properties=new Properties();
  17.         properties.setProperty("kaptcha.textproducer.char.string""123456789");//验证码字符范围
  18.         properties.setProperty("kaptcha.border.color""245,248,249");//图片边框颜色
  19.         properties.setProperty("kaptcha.textproducer.font.color""black");//字体颜色
  20.         properties.setProperty("kaptcha.textproducer.char.space""2");//文字间隔
  21.         properties.setProperty("kaptcha.image.width""125");//图片宽度
  22.         properties.setProperty("kaptcha.image.height""45");//图片高度
  23.         properties.setProperty("kaptcha.session.key""code");//session的key
  24.         properties.setProperty("kaptcha.textproducer.char.length""4");//长度
  25.         properties.setProperty("kaptcha.textproducer.font.names""宋体,楷体,微软雅黑");//字体
  26.         Config config=new Config(properties);
  27.         defaultKaptcha.setConfig(config);
  28.         return defaultKaptcha;
  29.     }
  30. }
  方法二、基于XML配置方式 1、在resources下创建myKaptcher.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">23456789ABCEFGHJKMNOPQRSTUVWXYZ</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.NoNoise</prop>
  23.                         <!--<prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.DefaultNoise</prop>-->
  24.                         <prop key="kaptcha.background.clear.from">185,56,213</prop>
  25.                         <prop key="kaptcha.background.clear.to">white</prop>
  26.                         <prop key="kaptcha.textproducer.char.space">3</prop>
  27.                     </props>
  28.                 </constructor-arg>
  29.             </bean>
  30.         </property>
  31.     </bean>
  32. </beans>
  2、然后在启动类Application中加载配置
  1. @EnableTransactionManagement// 启动注解事务管理,等同于xml配置方式的 <tx:annotation-driven />
  2. @SpringBootApplication
  3. @EnableScheduling//启动注解定时任务
  4. @MapperScan(basePackages = "com.liuyanzhao.mapper")
  5. @ImportResource(locations={"classpath:mykaptcha.xml"})
  6. public class Application extends SpringBootServletInitializer {
  7.     public static void main(String[] args) throws Exception {
  8.         SpringApplication.run(Application.class, args);
  9.     }
  10. }
  两种配置方式在springboot中均可,这里推荐前者。   具体参数配置如下
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
 

三、Controller

  1. package com.liuyanzhao.forum.controller.common;
  2. import java.awt.image.BufferedImage;
  3. import javax.imageio.ImageIO;
  4. import javax.servlet.ServletOutputStream;
  5. import lombok.extern.apachecommons.CommonsLog;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.web.bind.annotation.GetMapping;
  9. import com.google.code.kaptcha.Constants;
  10. import com.google.code.kaptcha.Producer;
  11. /**
  12.  * @author 言曌
  13.  * @date 2018/5/4 下午12:36
  14.  */
  15. @CommonsLog
  16. @Controller
  17. public class KaptchaController extends BaseController {
  18.     @Autowired
  19.     private Producer captchaProducer;
  20.     @GetMapping("/getKaptchaImage")
  21.     public void getKaptchaImage() throws Exception {
  22.         response.setDateHeader("Expires"0);
  23.         // Set standard HTTP/1.1 no-cache headers.
  24.         response.setHeader("Cache-Control""no-store, no-cache, must-revalidate");
  25.         // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
  26.         response.addHeader("Cache-Control""post-check=0, pre-check=0");
  27.         // Set standard HTTP/1.0 no-cache header.
  28.         response.setHeader("Pragma""no-cache");
  29.         // return a jpeg
  30.         response.setContentType("image/jpeg");
  31.         // create the text for the image
  32.         String capText = captchaProducer.createText();
  33.         // store the text in the session
  34.         //request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
  35.         //将验证码存到session
  36.         session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
  37.         log.info(capText);
  38.         // create the image with the text
  39.         BufferedImage bi = captchaProducer.createImage(capText);
  40.         ServletOutputStream out = response.getOutputStream();
  41.         // write the data out
  42.         ImageIO.write(bi, "jpg", out);
  43.         try {
  44.             out.flush();
  45.         } finally {
  46.             out.close();
  47.         }
  48.     }
  49. }
 

四、验证码显示

直接访问 getKaptchaImage 就能显示图片 http://localhost:8080/forum/getKaptchaImage       在页面中显示,只需要添加下面代码 HTML
  1. <img th:src="@{/getKaptchaImage}" width="80" height="34" class="captcha changeCaptcha pull-left margin-r-5" alt="验证码"/>
  2. <a href="javascript:void(0)" class="changeCaptcha">换一张</a>
JS
  1. //切换验证码
  2.  $(document).on('click', '.changeCaptcha', function () {
  3.      var url = _ctx + "/getKaptchaImage";
  4.      $(".captcha").attr("src", url);
  5.  })
  最终效果如下          
  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0