springboot 集成 kaptcha 验证码简单实例

avatar 2018年01月31日15:10:05 6 3172 views
博主分享免费Java教学视频,B站账号:Java刘哥
本文介绍 SpringBoot 使用 kaptcha 验证码,其实和 SpringBoot 没啥关系,主要是 kaptcha 的使用。  

一、准备工作

一个 SpringBoot 项目或者 SpringMVC 项目。 引入依赖
  1. <!--验证码kaptcha-->
  2.   <dependency>
  3.       <groupId>com.github.penggle</groupId>
  4.       <artifactId>kaptcha</artifactId>
  5.       <version>2.3.2</version>
  6.   </dependency>
 

二、加入 kaptcha 配置

方法一、 新建 CaptchaConfig.java
  1. package com.liuyanzhao.chuyun.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/1/30 下午11:31
  10.  */
  11. @Configuration
  12. public class CaptchaConfig {
  13.     @Bean(name="captchaProducer")
  14.     public DefaultKaptcha getKaptchaBean(){
  15.         DefaultKaptcha defaultKaptcha=new DefaultKaptcha();
  16.         Properties properties=new Properties();
  17.         properties.setProperty("kaptcha.border""yes");
  18.         properties.setProperty("kaptcha.border.color""105,179,90");
  19.         properties.setProperty("kaptcha.textproducer.font.color""blue");
  20.         properties.setProperty("kaptcha.image.width""125");
  21.         properties.setProperty("kaptcha.image.height""45");
  22.         properties.setProperty("kaptcha.session.key""code");
  23.         properties.setProperty("kaptcha.textproducer.char.length""4");
  24.         properties.setProperty("kaptcha.textproducer.font.names""宋体,楷体,微软雅黑");
  25.         Config config=new Config(properties);
  26.         defaultKaptcha.setConfig(config);
  27.         return defaultKaptcha;
  28.     }
  29. }
  方法二、 1、在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. </beans>
  2、在springboot启动类上引入这
  1. @SpringBootApplication
  2. @ImportResource(locations={"classpath:mykaptcha.xml"})
  3. public class Application {
  4.     public static void main(String[] args) {
  5.         SpringApplication.run(Application.class, args);
  6.     }
  7. }
   

三、显示验证码

TestController.java
  1. package com.liuyanzhao.chuyun.controller;
  2. import com.google.code.kaptcha.impl.DefaultKaptcha;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.ui.Model;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import javax.imageio.ImageIO;
  9. import javax.servlet.ServletOutputStream;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import javax.servlet.http.HttpSession;
  13. import java.awt.image.BufferedImage;
  14. import java.io.ByteArrayOutputStream;
  15. /**
  16.  * @author 言曌
  17.  * @date 2018/1/30 下午11:37
  18.  */
  19. @Controller
  20. public class TestController {
  21.     @Autowired
  22.     DefaultKaptcha defaultKaptcha;
  23.     /**
  24.      * 显示验证码
  25.      * @param request
  26.      * @param response
  27.      * @throws Exception
  28.      */
  29.     @RequestMapping("/defaultKaptcha")
  30.     public void defaultKaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
  31.         byte[] captchaChallengeAsJpeg = null;
  32.         ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
  33.         try {
  34.             //生产验证码字符串并保存到session中
  35.             String createText = defaultKaptcha.createText();
  36.             request.getSession().setAttribute("verifyCode", createText);
  37.             //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
  38.             BufferedImage challenge = defaultKaptcha.createImage(createText);
  39.             ImageIO.write(challenge, "jpg", jpegOutputStream);
  40.         } catch (IllegalArgumentException e) {
  41.             response.sendError(HttpServletResponse.SC_NOT_FOUND);
  42.             return;
  43.         }
  44.         //定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
  45.         captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
  46.         response.setHeader("Cache-Control""no-store");
  47.         response.setHeader("Pragma""no-cache");
  48.         response.setDateHeader("Expires"0);
  49.         response.setContentType("image/jpeg");
  50.         ServletOutputStream responseOutputStream =
  51.                 response.getOutputStream();
  52.         responseOutputStream.write(captchaChallengeAsJpeg);
  53.         responseOutputStream.flush();
  54.         responseOutputStream.close();
  55.     }
  56.     /**
  57.      * 映射 test.html
  58.      * @return
  59.      */
  60.     @GetMapping("/test")
  61.     public String test() {
  62.         return "/test";
  63.     }
  64.     /**
  65.      * 验证码输入验证
  66.      * @param model
  67.      * @param session
  68.      * @param verifyCode
  69.      * @return
  70.      */
  71.     @GetMapping("/verifyCode")
  72.     public String imgverifyControllerDefaultKaptcha(Model model, HttpSession session, String verifyCode) {
  73.         String captchaId = (String) session.getAttribute("verifyCode");
  74.         System.out.println("验证码是:" + captchaId);
  75.         System.out.println("用户输入的是:" + verifyCode);
  76.         if (!captchaId.equals(verifyCode)) {
  77.             System.out.println("输入错误");
  78.             model.addAttribute("info""错误的验证码");
  79.         } else {
  80.             System.out.println("输入正确");
  81.             model.addAttribute("info""正确");
  82.         }
  83.         return "/test";
  84.     }
  85. }
  test.html
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml"
  3.       xmlns:th="http://www.thymeleaf.org">
  4. <head>
  5.     <meta charset="UTF-8">
  6.     <title>kaptcha 测试</title>
  7. </head>
  8. <body>
  9. <h1 th:text="${info}"/>
  10. <div>
  11.     <img alt="验证码" onclick="this.src='/defaultKaptcha?d='+new Date()*1" src="/defaultKaptcha"/>
  12. </div>
  13. <form action="/verifyCode">
  14.     <input type="text" name="verifyCode"/>
  15.     <input type="submit" value="提交"/>
  16. </form>
  17. </body>
  18. </html>
 

效果图

访问 localhost:8080/test,可以看到有验证码,填写图中的验证码提交     显示错误的验证码     查看控制台信息,如我们所料     再次输入验证码,点提交,这次提交正确     再次查看控制台,验证码正确     本文链接:https://liuyanzhao.com/7433.html
  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

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

  

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