java使用kaptcha生成图片验证码

25 篇文章 1 订阅
21 篇文章 1 订阅

作为一个后端开发人员,平台安全是重中之重,对于平台中登陆的校验一直是斗智斗勇的存在,

因此增加一些人工的校验,对于攻击有很好的拦截,也能够很好的保证用户账号密码的安全

图片验证码效果图

test2

使用的pom包,如果使用的不是pom ,可以在网上下载相同的jar

<dependency>
    <groupId>com.github.axet</groupId>
    <artifactId>kaptcha</artifactId>
    <version>0.0.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
 其中有方法 RandomStringUtils.randomNumeric(5); 生成任意五位数字 
-->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Kaptcha配置文件

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;

/**
 * 生成验证码配置
 *
 * @author lwj
 * @since 2.1.0 2022-01-12
 */
@Configuration
public class KaptchaConfig {

    @Bean
    public DefaultKaptcha producer() {
        Properties properties = new Properties();
        properties.put("kaptcha.border", "no");
        properties.put("kaptcha.textproducer.font.color", "black");
        properties.put("kaptcha.textproducer.char.space", "5");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

Controller中调用的java方法

@GetMapping("captcha.jpg")
public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setHeader("Cache-Control", "no-store, no-cache");
    response.setContentType("image/jpeg");
    //生成文字验证码 生成5位中英文混合的验证码
    //String code = producer.createText();
    //生成5位数字的验证码
    String code = RandomStringUtils.randomNumeric(5);
    //request获取ip,保存到redis中【缺点:统一大型局域网下,公用一个公网IP】
    //校验也可以使前端传输一个UUID,校验图片二维码时可以使用UUID查询出生成的验证码
    ServletOutputStream out = response.getOutputStream();
    //获取图片验证码
    BufferedImage image = producer.createImage(code);
    ImageIO.write(image, "jpg", out);
    out.close();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值