springboot整合kaptcha验证码 springboot整合kaptcha验证码的代码实例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

springboot整合kaptcha验证码 springboot整合kaptcha验证码的代码实例

贪挽懒月   2021-03-31 我要评论

前言:

关于kaptcha简介以及spring整合kaptcha,我在另一篇文章中已详细讲解,请参考:spring整合kaptcha验证码。

本文将介绍springboot整合kaptcha的两种方式。

开发工具及技术:

1、idea 2017
2、springboot 2.0.2
3、kaptcha

正式开始:

方式一:通过kaptcha.xml配置

1、用idea新建一个spring Initializr

2、添加kaptcha的依赖:

<!-- kaptcha验证码 -->
    <dependency>
    <groupId>com.github.penggle</groupId>
      <artifactId>kaptcha</artifactId>
      <version>2.3.2</version>
    </dependency>

3、在resources下面新建kaptcha.xml,内容如下:

kaptcha.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">
  <!-- 生成kaptcha的bean-->
  <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">
          <!--设置kaptcha属性 -->
          <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>

注:kaptcha.xml中的内容其实就是和spring 整合kaptcha时spring-kaptcha.xml中内容一样,就是将kaptcha交给spring容器管理,设置一些属性,然后要用的时候直接注入即可。

4、加载kaptcha.xml:

在springboot启动类上加上@ImportResource(locations = {"classpath:kaptcha/kaptcha.xml"}),加了这个注解,springboot就会去加载kaptcha.xml文件。注意kaptcha.xml的路径不要写错,classpath在此处是resources目录。

5、编写controller用于生成验证码:

CodeController.java

@Controller
public class CodeController {
  @Autowired
  private Producer captchaProducer = null;
  @RequestMapping("/kaptcha")
  public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");
    response.setContentType("image/jpeg");
    //生成验证码
    String capText = captchaProducer.createText();
    session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
    //向客户端写出
    BufferedImage bi = captchaProducer.createImage(capText);
    ServletOutputStream out = response.getOutputStream();
    ImageIO.write(bi, "jpg", out);
    try {
      out.flush();
    } finally {
      out.close();
    }
  }
}

注:在这个controller径注入刚刚kaptcha.xml中配置的那个bean,然后就可以使用它生成验证码,以及向客户端输出验证码;记住这个类的路由,前端页面验证码的src需要指向这个路由。

6、新建验证码比对工具类:

CodeUtil.java

public class CodeUtil {
  /**
   * 将获取到的前端参数转为string类型
   * @param request
   * @param key
   * @return
   */
  public static String getString(HttpServletRequest request, String key) {
    try {
      String result = request.getParameter(key);
      if(result != null) {
        result = result.trim();
      }
      if("".equals(result)) {
        result = null;
      }
      return result;
    }catch(Exception e) {
      return null;
    }
  }
  /**
   * 验证码校验
   * @param request
   * @return
   */
  public static boolean checkVerifyCode(HttpServletRequest request) {
    //获取生成的验证码
    String verifyCodeExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
    //获取用户输入的验证码
    String verifyCodeActual = CodeUtil.getString(request, "verifyCodeActual");
    if(verifyCodeActual == null ||!verifyCodeActual.equals(verifyCodeExpected)) {
      return false;
    }
    return true;
  }
}

注:这个类用来比对生成的验证码与用户输入的验证码。生成的验证码会自动加到session中,用户输入的通过getParameter获得。注意getParameter的key值要与页面中验证码的name值一致。

7、使用验证码:

①Controller

HelloWorld.java

@RestController
public class HelloWorld {
  @RequestMapping("/hello")
  public String hello(HttpServletRequest request) {
    if (!CodeUtil.checkVerifyCode(request)) {
      return "验证码有误!";
    } else {
      return "hello,world";
    }
  }
}

②页面

hello.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script type="text/javascript">
    function refresh() {
      document.getElementById('captcha_img').src="/kaptcha?"+Math.random();
    }
  </script>
</head>
<body>
<form action="/hello" method="post">
  验证码: <input type="text" placeholder="请输入验证码" name="verifyCodeActual">
  <div class="item-input">
    <img id="captcha_img" alt="点击更换" title="点击更换"
       onclick="refresh()" src="/kaptcha" />
  </div>
  <input type="submit" value="提交" />
</form>

</body>
</html>

注意:验证码本质是一张图片,所以用<img >标签,然后通过src = "/kaptcha"指向生成验证码的那个controller的路由即可;通过onclick = “refresh()”调用js代码实现点击切换功能;<input name = "verifyCodeActual ">中要注意name的值,在CodeUtil中通过request的getParameter()方法获取用户输入的验证码时传入的key值就应该和这里的name值一致。

8、测试:

输入正确的验证码


验证通过


输入错误的验证码


验证未通过


方式二:通过配置类来配置kaptcha

1、配置kaptcha

相比于方式一,一增二减。

减:

①把kaptcha.xml删掉
②把启动类上的@ImportResource(locations = {"classpath:kaptcha/kaptcha.xml"})注解删掉

增:

①新建KaptchaConfig配置类,内容如下:

KaptchaConfig.java

@Configuration
public class KaptchaConfig {
  @Bean
  public DefaultKaptcha getDefaultKaptcha(){
    DefaultKaptcha captchaProducer = new 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);
    captchaProducer.setConfig(config);
    return captchaProducer;

  }
}

注:这个类用来配置Kaptcha,就相当于方式一的kaptcha.xml,把kaptcha加入IOC容器,然后return 回一个设置好属性的实例,最后注入到CodeController中,在CodeController中就可以使用它生成验证码。要特别注意return captchaProducer;与private Producer captchaProducer = null;中captchaProducer名字要一样,不然就加载不到这个bean。

2、测试:

输入正确的验证码:


验证通过


输入错误的验证码


验证未通过


为了说明两次的验证码是基于两种方式生成的,方式一和方式二的验证码我设置了不同的属性,从图片中可以看出两次验证码的颜色、干扰线、背景等都有不同。

总结:

1、过程梳理:

不论是哪种方式,都是先把kaptcha加入spring容器,即要有一个kaptcha的bean;再新建一个controller,把kaptcha的bean注入到controller中用于生成验证码;然后需要有一个比对验证码的工具类,在测试的controller中调用工具类进行验证码比对;最后在前端页面只需要用一个<img src = "/生成验证码的controller的路由">即可获取验证码,通过给这个img标签加点击事件就可实现“点击切换验证码”。

2、与spring整合kaptcha对比

spring整合kaptcha也介绍了两种方式,在web.xml中配置最简洁,不需要写生成验证码的controller,在页面中直接用src指向web.xml中kaptcha的servlet 的<url-pattern >的值即可。

springboot整合kaptcha的两种方式都类似于spring整合kaptcha的第二种方式,都是先配置bean,然后用controller生成验证码,前端用src指向这个controller,不同之处在于:假如生成验证码的controller路由为/xxx,那么spring 整合kaptcha时src = “xxx.jpg”,springboot整合kaptcha时src = "/xxx"。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们