Captcha生成验证码,docker部署时字体包空指针异常

依赖

        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>

配置类

package cn.penghf.lovemaster.config;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
public class KaptchaConfiguration {
    @Bean(name="captchaProducer")
    public DefaultKaptcha getKaptchaBean(){
        DefaultKaptcha defaultKaptcha=new DefaultKaptcha();
        Properties properties=new Properties();
        properties.setProperty("kaptcha.image.width", "160");
        properties.setProperty("kaptcha.image.height", "50");
        properties.setProperty("kaptcha.border", "no");
        //properties.setProperty("kaptcha.border.color", "105,179,90");
        properties.setProperty("kaptcha.textproducer.font.color", "255,103,51");
        properties.setProperty("kaptcha.textproducer.font.size","43");
        properties.setProperty("kaptcha.noise.color", "152,204,102");
        properties.setProperty("kaptcha.background.clear.from","130,129,179");
        properties.setProperty("kaptcha.background.clear.to","182,188,242");
        //properties.setProperty("kaptcha.session.key", "code");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.char.space","5");
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        properties.setProperty("kaptcha.obscurificator.impl","com.google.code.kaptcha.impl.ShadowGimpy");
        properties.setProperty("kaptcha.background.impl","com.google.code.kaptcha.impl.DefaultBackground");
        Config config=new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

Controller

package cn.penghf.lovemaster.controller.security;

import cn.penghf.common.entity.security.Person;
import cn.penghf.common.utils.PKGenerator;
import cn.penghf.lovemaster.constants.CookieConstants;
import cn.penghf.lovemaster.constants.RedisConstants;
import cn.penghf.lovemaster.service.security.PersonService;
import cn.penghf.lovemaster.utils.http.CookieUtil;
import cn.penghf.lovemaster.utils.redis.RedisUtil;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Api("登录控制")
@RestController
@RequestMapping("/master/security/login")
@Slf4j
public class LoginController {

    @Autowired
    private Producer captchaProducer;

    @ApiOperation("验证码生成")
    @RequestMapping("/getValidateCode")
    public void getValidateCode(HttpServletResponse response){
        response.setDateHeader("Expires", 0);

        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");
        // create the text for the image
        String capText = captchaProducer.createText();
        log.info("验证码:"+capText);
        // store the text in the session
        String validateCodeId = PKGenerator.generateId();
        RedisUtil.set(String.format(RedisConstants.VALIDATECODE_PREFIX,validateCodeId),capText,RedisConstants.EXPIRE);
        //设置token到cookie
        CookieUtil.set(response, CookieConstants.VALIDATECODE , validateCodeId,CookieConstants.EXPIRE);
        // create the image with the text
        BufferedImage bi = captchaProducer.createImage(capText);
        // write the data out
        ServletOutputStream os = null;
        try {
            os = response.getOutputStream();
            ImageIO.write(bi, "jpg", os);
            os.flush();
            //return new RespBody(RespBody.StatusEnum.OK);
        } catch (IOException e) {
            log.error("获取验证码输出流异常",e);
            //return new RespBody(RespBody.StatusEnum.ERROR,"验证码获取异常");
        }finally {
            try {
                os.close();
            } catch (IOException e) {
                log.error("验证码输出流关闭异常",e);
                //return new RespBody(RespBody.StatusEnum.ERROR,"验证码获取异常");
            }
        }
    }
}

系统部署测试

docker部署

plugin

            <!-- Docker maven plugin -->
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <imageName>${docker.image.prefix}.${project.artifactId}</imageName>
                    <dockerDirectory>src/main/docker</dockerDirectory>
                    <resources>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}</directory>
                            <include>${project.build.finalName}.jar</include>
                        </resource>
                    </resources>
                </configuration>
            </plugin>
            <!-- Docker maven plugin -->

Dockerfile

FROM openjdk:8-jdk-alpine
VOLUME /tmp
##时区
RUN echo "Asia/Shanghai" > /etc/timezone

#captcher 字体包
RUN set -xe \
&& apk --no-cache add ttf-dejavu fontconfig

ADD love-master-0.0.1-SNAPSHOT.jar love-master.jar
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/love-master.jar"]

openjdk:8-jdk-alpine 没有相关字体包,调用createImage()方法时,会报空指针异常,此处已经指定docker容器安装字体包

kaptcha相关配置参数参考

参考文章:

Captcha生成与使用,解决Docker font - 简书

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
在 Koa2 中使用 svg-captcha 生成验证码可以按照以下步骤进行: 1. 安装 svg-captcha 和 koa-svgrouter 模块 ```bash npm install svg-captcha koa-svgrouter --save ``` 2. 在 Koa2 应用中引入相关模块 ```javascript const Koa = require('koa'); const Router = require('koa-router'); const svgrouter = require('koa-svgrouter'); const svgCaptcha = require('svg-captcha'); const app = new Koa(); const router = new Router(); ``` 3. 设置路由,生成验证码 ```javascript router.get('/captcha', async (ctx, next) => { const captcha = svgCaptcha.create(); ctx.session.captcha = captcha.text; ctx.type = 'svg'; ctx.body = captcha.data; }); ``` 4. 添加 SVG 路由 ```javascript app.use(svgrouter('/captcha/:id', { useSession: true, sessionName: 'captcha' })); ``` 5. 在需要使用验证码的地方,可以通过如下代码获取验证码图片 ```html <img src="/captcha/1" /> ``` 注意,上述代码中的数字 1 是路由参数,可以自行设置。 6. 验证验证码 在需要验证验证码的地方,可以通过如下代码获取用户输入的验证码,并与之前生成验证码进行比较。 ```javascript const userCaptcha = ctx.request.body.captcha; if (userCaptcha.toLowerCase() === ctx.session.captcha.toLowerCase()) { // 验证码输入正确 } else { // 验证码输入错误 } ``` 以上就是使用 svg-captcha 生成验证码的基本步骤。需要注意的是,在生成验证码和验证验证码都需要使用到 Koa2 的 session 功能,因此需要在应用中添加相关中间件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

day day day ...

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值