0

Springboot3整合使用ja-captcha行为验证码解决方案 - Java小学生丶

 1 year ago
source link: https://www.cnblogs.com/hanzhe/p/17337168.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Springboot3整合使用ja-captcha行为验证码解决方案

截止到目前,Springboot最新稳定版本已经迭代到3.0.5,而我们项目中使用的行为验证码框架ja-captcha还没有适配Springboot3,码云上类似的请求也没有得到过回应,于是决定自己动手适配一下,研究下来发现适配3.x并没有那么难,这里记录一下适配过程,希望能帮到他人

image

首先搭建一个Springboot2的项目,以最简单的方法整合验证码,这里我选择使用springboot2.7.5ja-captcha1.3.0,在Maven中添加依赖后直接启动项目即可

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.5</version>
    </parent>
    <groupId>site.hanzhe.boot3.captcha</groupId>
    <artifactId>springboot3-ja-captcha</artifactId>
    <version>0.0.1</version>
    <description>Springboot3整合ja-captcha行为验证码解决方案</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.anji-plus</groupId>
            <artifactId>spring-boot-starter-captcha</artifactId>
            <version>1.3.0</version>
        </dependency>
    </dependencies>

</project>
image

可以看到已经整合成功了,而且调用接口测试也一切正常,现在将Springboot版本改成3.0.5,然后刷新Maven后重启一下项目试试看,发现控制台已经不打印ja-captcha的日志了,而且接口也返回404

image

在整合之前,我们需要了解一下Springboot3.x的两个重要的变化

第一个变化是Springboot3以JakartaEE 9为基准并支持JakartaEE 10,其实Jakarta就是Java,Oracle将JavaEE移交给了Eclipse基金会,并不允许其使用原本的java名称,所以Java改名为Jakarta,原javax包名也修改为了jakarta

第二个变化是Springboot自动配置文件的变更,Springboot3废弃了factories的自动配置,改为使用imports文件

了解这两点后我们回到整合验证码的项目中,首先可以观察到最明显的一点,启动项目后控制台不在打印ja-captcha的日志了,这就代表自动配置并没有生效,在外部库中找到ja-captcha的自动配置,发现它是使用factories进行自动配置的,该方法已经失效,我们需要创建新的自动配置文件来启用它

在resource目录下新建META-INF/spring两个目录,在目录下添加自动配置文件,并将ja-captcha的自动配置类添加进去然后重启项目查看效果,文件名太长我就放在代码块中了

# 文件名
org.springframework.boot.autoconfigure.AutoConfiguration.imports

# 文件内容
com.anji.captcha.config.AjCaptchaAutoConfiguration
image

可以看到项目启动报错了,不过不用担心,报错是好事儿,说明自动配置生效了,提取报错中的主要信息,是创建captchaController这个Bean的时候报错了,报错的原因是没有找到javax/servlet/http/HttpServletRequest这个类,因为Springboot3中javax的包名统一修改为了jakarta,所以这个类会找不到

这里直接使用替换法简单粗暴的解决这个问题,找到报错的这个类,在项目中创建一个相同包名的的类,将里面的javax替换为jakarta,这样在创建Bean的时候Java找到的类是我们自己的jakarta的类,就不会调用旧的javax的类了

image

替换后重启项目查看效果,可以发现项目已经启动成功了,并且控制台打印了ja-captcha的启动日志,调试接口也成功了

本文使用笨方法在Springboot3中使用ja-captcha,还是希望作者早日做适配


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK