SpringBoot整合kaptcha验证码过程(复制粘贴即可用)

本文主要是介绍SpringBoot整合kaptcha验证码过程(复制粘贴即可用),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《SpringBoot整合kaptcha验证码过程(复制粘贴即可用)》本文介绍了如何在SpringBoot项目中整合Kaptcha验证码实现,通过配置和编写相应的Controller、工具类以及前端页...

SpringBoot整合kaptcha验证码

前面学习了几种样式的验证码验证,Java实现kaptcha网页验证码验证,你会吗???

作为一个目前以Java后端的为方向的小白,当然要写一个关于SpringBoot整合kaptcha来实现验证码的操作啦,而且以后要用到该功能的话直接复制粘贴就可以啦~ 

程序目录参考

SpringBoot整合kaptcha验证码过程(复制粘贴即可用)

1、首先用idea新建一个spring Initializr 

2、添加依赖: 

<!-- 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中注入其对象。

第一种方式

  • 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-3.1.xsd">
    <!-- Kaptcha组件配置 -->
    <bean id="kaptchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
        <property name="config">
            <bean class="com.google.code.kaptcha.util.Config">
                <constructor-arg>
                    <props>
                        <!-- 验证码宽度 -->
                        <prop key="kaptcha.image.width">120</prop>
                        <!-- 验证码高度 -->
                        <prop key="kaptcha.image.height">50</prop>
                        <!-- 生成验证码内容范围 -->
                        <prop key="kaptcha.textproducer.char.string">0123456789AKWUEHPMRX</prop>
  China编程                      <!-- 验证码个数 -->
                        <prop key="kaptcha.textproducer.char.length">4</prop>
                        <!-- 是否有边框 -->
                        <prop key="kaptcha.border">no</prop>
                        <!-- 边框颜色 -->
                        <prop key="kaptcha.border.color">105,179,90</prop>
                        <!-- 边框厚度 -->
                        <prop key="kaptcha.border.thickness">1</prop>
                        <!-- 验证码字体颜色 -->
                        <prop key="kaptcha.textproducer.font.color">yellow</prop>
                        <!-- 验证码字体大小 -->
                        <prop key="kaptcha.textproducer.font.size">30</prop>
                        <!-- 验证码所属字体样式 -->
                        <prop key="kaptcha.textproducer.font.names">楷体</prop>
                        <!-- 干扰线颜色 -->
                        <prop key="kaptcha.noise.color">black</prop>
                        <!-- 验证码文本字符间距 -->
                        <prop key="kaptcha.textproducer.char.space">8</prop>
                        <!-- 图片样式 :阴影-->
                        <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.ShadowGimpy</prop>
                    </props>
                </constructor-arg>
            </bean>
        </property>
    </bean>
</beans>

在springboot启动类上加上@ImportResource(locations = {“classpath:mykaptcha.xml”}),加了这个注解,springboot就会去加载kaptcha.xml文件

  • springboot启动类:
@SpringBootApplication
@ImportResource(locations = {"classpath:mykaptcha.xml"})
public class SpringbootKaptchaApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootKaptchaApplication.class, args);
    }
}

第二种方式

写一个Kaptcha配置类KaptchaConfig。

  • KaptchaConfig.java:
@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;
    }
}

这个类用来配置Kaptcha,就相当于方法一的mykaptcha.xml,把mykaptcha加入IOC容器,然后return 回一个设置好属性的实例,最后注入到KaptchaController中,在KaptchaController中就可以使用它生成验证码。

上面的两种方法选择其一即可,下面我用XML的方式进行操作。 

编写controller用于生成验证码

  • KaptchaController.java:
@Controller
public class KaptchaController {
    //第二种方法
    //@Qualifier("getDefaultKaptcha")
    @Autowired
    private Producer captchaProducer = null;
    @RequestMapping("/mykaptcha")
    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 CAbHSM= captchaProducer.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        //向客户端写php出
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}
  • HelloKaptcha.java:
@RestController
public class HelloKaptcha {
    @RequestMapping("/hello")
    public String hello(HttpServletRequest request) {
        if (!CodeUtil.checkVerifyCode(request)) {
            return "验证码有误!!!";
        } else {
            return "欢迎使用!!!";
        }
    }
}

编写工具类util

  • CodeUtil.java:
public class CodeUtil {
/**
 * 将获取到的前端参数转为string类型
 */
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;
    }catchpython(Exception e) {
        return null;
    }
}
/**
 * 验证码校验
 */
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获得。

  • 前端页面:index.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="/mykaptcha?"+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="SpringBoot整合kaptcha验证码过程(复制粘贴即可用)" title="SpringBoot整合kaptcha验证码过程(复制粘贴即可用)"
             onclick="refresh()" src="/mykaptcha" />
    </div>
    <input type="submit" value="提交" />
</form>
</body>
</html>

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

效果为:

SpringBoot整合kaptcha验证码过程(复制粘贴即可用)

SpringBoot整合kaptcha验证码过程(复制粘贴即可用)

总结:

在用springboot整合kaptcha时操作并不顺利,因为一开始我并不是把所有的程序写到启动类的同一个包下,而是写到了和同级的包下,如:

SpringBoot整合kaptcha验证码过程(复制粘贴即可用)

发现了吗???

SpringBoot整合kaptcha验证码过程(复制粘贴即可用)

是的,我居然把使用的程序,没有写在启动类的包下,就这个低级的错误让我卡了一下午,害,说多了都是泪;因为没有写在启动类的包下,springboot识别不到,就会出现运行时网页的验证码无法显示的情况,如下:

SpringBoot整合kaptcha验证码过程(复制粘贴即可用)

最后在师兄的帮助下才解决了,感谢师兄~

最后附个表以便查阅自己想更改的验证码图形:

SpringBoot整合kaptcha验证码过程(复制粘贴即可用)SpringBoot整合kaptcha验证码过程(复制粘贴即可用)

总结

关于SpringBoot整合kaptcha验证码的使用就到这里。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程China编程(www.chinasem.cn)。

这篇关于SpringBoot整合kaptcha验证码过程(复制粘贴即可用)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1152944

相关文章

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.

java中long的一些常见用法

《java中long的一些常见用法》在Java中,long是一种基本数据类型,用于表示长整型数值,接下来通过本文给大家介绍java中long的一些常见用法,感兴趣的朋友一起看看吧... 在Java中,long是一种基本数据类型,用于表示长整型数值。它的取值范围比int更大,从-922337203685477

MySQL存储过程之循环遍历查询的结果集详解

《MySQL存储过程之循环遍历查询的结果集详解》:本文主要介绍MySQL存储过程之循环遍历查询的结果集,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言1. 表结构2. 存储过程3. 关于存储过程的SQL补充总结前言近来碰到这样一个问题:在生产上导入的数据发现

java Long 与long之间的转换流程

《javaLong与long之间的转换流程》Long类提供了一些方法,用于在long和其他数据类型(如String)之间进行转换,本文将详细介绍如何在Java中实现Long和long之间的转换,感... 目录概述流程步骤1:将long转换为Long对象步骤2:将Longhttp://www.cppcns.c

SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程

《SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程》LiteFlow是一款专注于逻辑驱动流程编排的轻量级框架,它以组件化方式快速构建和执行业务流程,有效解耦复杂业务逻辑,下面给大... 目录一、基础概念1.1 组件(Component)1.2 规则(Rule)1.3 上下文(Conte